How to sort array of primitive types in ascending and descending order ?

We can sort array of primitive types using Array.Sort() and Array.Reverse() in ascending and descending order

Example :

// sort int array in ascending order


int[] intArray = new int[5] { 8, 10, 2, 6, 9 };
Array.Sort(intArray);
// write array
foreach (int i in intArray) Console.Write(i + " "); // output: 2  6 8 9 10

// sort int array in descending order


int[] intArray = new int[5] { 8, 10, 2, 6, 9 };
Array.Sort(intArray);
Array.Reverse(intArray);

// write array
foreach (int i in intArray) Console.Write(i + " "); // output: 10 9 8 6 2

No comments:

Popular Posts