Write a program to sort 20 decimal numbers in decreasing order and print the
result.
i have solution but lengthy.

``````decimal[] arr = { 12.3m, 45.2m, 5.4m, 23.44m, 43.21m, 31.34m, 4.3m, 21.3m,
34.2m, 32.1m, 44.2m, 6.4m, 64.3m, 3.4m, 5.32m, 32.345m, 4.34m, 23.4m,
45.234m, 5.31m };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("\n--Number in decreasing order--\n");
int count = 0;
while (count < arr.Length - 1)
{
if (arr[count] < arr[count + 1])
{
decimal temp = arr[count];
arr[count] = arr[count + 1];
arr[count + 1] = temp;
count = 0;
continue;
}
count++;
}``````
4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Diamonddrake

use this...

``````decimal[] arr = { 12.3m, 45.2m, 5.4m, 23.44m, 43.21m };
Array.Sort(arr);
Array.Reverse(arr);``````

I did an example of sorting number, and I used a generic list. I copied your values from decimal array to list<decimal> and did what you have requested.
I hope you like it. Its fast and simple - and it works :)

``````private void method()
{
decimal[] arr = new decimal[] { 12.3m, 45.2m, 5.4m, 23.44m, 43.21m, 31.34m, 4.3m, 21.3m, 32.1m, 44.2m,
6.4m, 64.3m, 3.4m, 5.32m, 32.345m, 4.34m, 23.4m, 45.234m, 5.31m };
List<decimal> list = new List<decimal>();
for (int i = 0; i < arr.Length; i++)
{
});
//pG.aL = pG.aL.OrderBy(a => a.number).ToList();
list = list.OrderBy(a => a).ToList();
list.Reverse();
}``````

Mitja

The simplest solution would be to just call sort on the array, and if necessary reverse it as posted above, but there becomes a sorting issues between logical and natural order. if the decimals are not padded with zeros, it could get out of order. as in 10,1,2,3...9 instead of 1,2,3...9,10 because of that logical something before nothing clause.

this is simply overcome by using a numericcomparer class

``````NumericComparer ns = new NumericComparer();
Array.Sort(arraytosort, ns);
arraytosort.Reverse();``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.