The Sort() method is used to sort a String Array in Ascending order.
public class MyApplication { public static void Main(string[] args) { string[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"}; System.Array.Sort(arr); System.Console.WriteLine("The Sorted Array in ascending order is : "); foreach (string str in arr) { System.Console.WriteLine(str); } } }
So, in the above code we have created a Array and initialised to the variable arr.
string[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"};
Below is how the values are positioned in the Array,
Then we have used the System.Array.Sort() method to sort the Array arr in ascending order.
System.Array.Sort(arr);
And the Array arr gets sorted with John as the first value, Kriti second and Mohan as the third, Paul as fourth and Salim as the fifth value.
And we get the below output.
Even here the sort() method is used to sort the numbers in Increasing Order.
public class MyApplication { public static void Main(string[] args) { int[] arr = {5, 3, 2, 4}; System.Array.Sort(arr); System.Console.WriteLine("The Sorted Array in ascending order is : "); foreach (int str in arr) { System.Console.WriteLine(str); } } }
So, in the above code we have created an Integer Array and initialised to the variable arr.
int[] arr = {5, 3, 2, 4};
Below is how the values are positioned in the Array,
Then we have used the Ints() Method from the sort package to sort the Array arr in increasing order.
System.Array.Sort(arr);
And the numbers in the Array arr gets sorted.
And we get the below output.
To sort an array in descending order, we will perform a trick.
Let us see in the below example.
public class MyApplication { public static void Main(string[] args) { int[] arr = {5, 3, 2, 4}; System.Array.Sort(arr); System.Array.Reverse(arr); System.Console.WriteLine("The Sorted Array in descending order is : "); foreach (int str in arr) { System.Console.WriteLine(str); } } }
So, in the above code, all we have done is, used the Sort() method to sort the array in ascending order.
System.Array.Sort(arr);
Then we have used, the Reverse() method to reverse the elements of the array.
System.Array.Reverse(arr);
And we get the array elements sorted in descending order.