- Try Code Live
-
Sort an Integer Array
-
Sorting an array means arranging its elements in a specific order — most commonly in ascending (small to large) or descending (large to small) order.
Example:
In C#, the simplest and most widely used way to sort an integer array is by using the built-in Array.Sort() method.
What is Array.Sort()?
Array.Sort()is a static method provided by the System.Array class.
It automatically organizes the elements of a one-dimensional array in ascending order, without needing to write any custom sorting logic.
Output:int[] numbers = { 58, 3, 5, 23, 98, 10 }; // Sorting array in ascending order Array.Sort(numbers); foreach (int num in numbers) { Console.WriteLine(num); }
Sorting in Descending Order3 5 10 23 58 98
Example:Array.Sort()sorts in ascending order by default.
To sort in descending order, simply use Array.Reverse() after sorting
Output:int[] numbers = { 58, 3, 5, 23, 98, 10 }; Array.Sort(numbers); Array.Reverse(numbers); foreach (int num in numbers) { Console.WriteLine(num); }98 58 23 10 5 3
Write this program without inbuild methods i.e Sort() and Reverse() method.
Compare each element with the rest of the elements and swap them based on the required order. By doing this repeatedly, the correct element is placed at the correct position step by step. This approach is similar to Selection Sort."
Example:
Output:var val = new int[] { 58, 3, 5, 23, 98, 10 }; for (int i = 0; i < val.Length - 1; i++) { for (int j = i + 1; j < val.Length; j++) { if (val[i] < val[j]) // only change the comparison { int temp = val[i]; val[i] = val[j]; val[j] = temp; } } } foreach (var item in val) { Console.WriteLine(item); }
Logic Explanation98 58 23 10 5 3
We are arranging numbers without using Sort() or any inbuilt method.
So we compare each element with every other element and swap them to place them in correct order.