Reputation:
I have a working implementation of the insertion sort in c#, however i need the values to be stored in decreasing order. My current implementation gives me the numbers in a increasing order. But im unsure on how to reverse it. A is my array.
for (i = 1; i < A.Length; i++)
{
int value = A[i];
j = i - 1;
while ((j >= 0) && (A[j].CompareTo(value) > 0))
{
A[j + 1] = A[j];
j--;
}
A[j + 1] = value;
}
Console.WriteLine("\nSorted\n");
foreach (int x in A)
{
Console.WriteLine(x);
}
Upvotes: 1
Views: 2159
Reputation: 1049
Change this:
while ((j >= 0) && (A[j].CompareTo(value) > 0))
with this:
while ((j >= 0) && (A[j].CompareTo(value) < 0))
Upvotes: 4
Reputation: 23300
To reverse the algorithm, simply reverse the comparison
while ((j >= 0) && (A[j].CompareTo(value) > 0))
to this
while ((j >= 0) && (A[j].CompareTo(value) < 0)) // note that it reads '< 0'
to reverse the condition on which you're checking.
Upvotes: 0
Reputation: 4183
You can use Linq to sort your array:
A.OrderBy(x => x);
Or sorting it descending (reversed):
A.OrderByDescending(x => x);
Upvotes: 2
Reputation: 460228
You want to reverse the array? Use Array.Reverse
:
Array.Reverse(A);
If you instead want to order it by the numbers, you can use LINQ:
A = A.OrderBy(i => i).ToArray();
A = A.OrderByDescending(i => i).ToArray();
If the array is already ordered Array.Reverse
is more efficient.
Upvotes: 1