Wednesday, 16 November 2011

Sorting array of primitive types in C#


In C# array can be sorted using static method Array.Sort which internally use Quicksort algorithm.
To sort array of primitive types such as int, double or string use method Array.Sort(Array) with the array as a paramater. The primitive types implements interface IComparable, which is internally used by the Sort method (it calls IComparable.Com­pareTo method).

Ex: Sort int array
// declare int array
int[] intArray = new int[5] { 8, 10, 2, 6, 3 };
// sort int array
Array.Sort(intArray);
// write array
foreach (int i in intArray) Console.Write(i + " ");  
// output is: 2 3 6 8 10
  
Ex: Sort string array
// sort string array
string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };
Array.Sort(stringArray);
// write array
foreach (string str in stringArray) Console.Write(str + " "); 
// output is: A B X Y Z

No comments:

Post a Comment