I have a small array of ints. I want to reorder the array from largest to smallest. Is there a method to do this?
+2
A:
You can do it using Array
Sort
& Reverse
:
Array.Sort(array);
Array.Reverse(array);
Example:
[Test]
public void Test()
{
var array = new[] { 1, 3, 2 };
Array.Sort(array);
Array.Reverse(array);
CollectionAssert.AreEquivalent(new[] { 3, 2, 1 }, array);
}
Elisha
2009-11-28 09:01:27
http://msdn.microsoft.com/en-us/library/system.array.sort%28VS.71%29.aspxand http://msdn.microsoft.com/en-us/library/system.array.reverse%28VS.71%29.aspx
o.k.w
2009-11-28 09:03:13
+5
A:
You could use Array.Sort:
int[] array = new[] { 1, 3, 2 };
Array.Sort(array, (x, y) => y.CompareTo(x));
As far as complexity is concerned:
On average, this method is an O(n log n) operation, where n is the Length of array; in the worst case it is an O(n ^ 2) operation
Darin Dimitrov
2009-11-28 09:04:08
+1
A:
You can try something like this
int[] ints = new int[] {1, 2, 3, 4, 1, 2, 3};
var sorted = ints.OrderBy(i => i);
Found at Sort array of items using OrderBy<>
astander
2009-11-28 09:14:26