How to Sort an Array in C# | Array.Sort() Method Set – 1
Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:
- Sort<T>(T[]) Method
- Sort<T>(T[], IComparer<T>) Method
- Sort<T>(T[], Int32, Int32) Method
- Sort<T>(T[], Comparison<T>) Method
- Sort(Array, Int32, Int32, IComparer) Method
- Sort(Array, Array, Int32, Int32, IComparer) Method
- Sort(Array, Int32, Int32) Method
- Sort(Array, Array, Int32, Int32) Method
- Sort(Array, IComparer) Method
- Sort(Array, Array, IComparer) Method
- Sort(Array, Array) Method
- Sort(Array) Method
- Sort<T>(T[], Int32, Int32, IComparer<T>) Method
- Sort<TKey,TValue>(TKey[], TValue[]) Method
- Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Method
- Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Method
- Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method
In this article, we will discuss the first 4 methods.
Sort an Array in C#
1. Sort<T>(T[]) Method
This method sorts the elements in an Array using the IComparable<T> generic interface implementation of each element of the Array.
Syntax:
Array.Sort<T>(T[] array);
Parameter: T[] array is a one-dimensional array of type T that you want to sort, T can be any type that implements the IComperable<T> interface.
Return Type: This method does not return a value. it sorts the array in place.
Exceptions:
- ArgumentNullException: If the array is null.
- InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface.
Example: This example demonstrates how to sort an array, perform a binary search for specific elements and determine their potential insertion positions in a sorted array.
// C# Program to demomstrates the use
// of the Array.Sort<T>(T[]) Method
using System;
class Geeks
{
public static void Main()
{
// array elements
string[] arr = new string[5] { "A", "D", "X", "G", "M" };
// Display original array
Console.WriteLine("Original Array:");
foreach (string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort:");
// Sorting the array
Array.Sort(arr);
// Display sorted array
foreach (string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinary Search for 'B':");
// Binary Search for "B"
int index = Array.BinarySearch(arr, "B");
sortT(arr, index);
Console.WriteLine("\nBinary Search for 'F':");
// Binary Search for "F"
index = Array.BinarySearch(arr, "F");
sortT(arr, index);
}
public static void sortT<T>(T[] arr, int index)
{
// If the index is negative, it represents the
// bitwise complement of the next larger element
if (index < 0)
{
// Convert to the actual index of
// the next larger element
index = ~index;
if (index == 0)
Console.WriteLine("Element would be inserted at the beginning of the array.");
else
Console.WriteLine($"Element would be inserted between {arr[index - 1]} and {arr[index]}.");
if (index == arr.Length)
Console.WriteLine("Element would be inserted at the end of the array.");
}
else
{
Console.WriteLine($"Element 'B' or 'F' found at index {index}.");
}
}
}
Output
Original Array: A D X G M After Sort: A D G M X Binary Search for 'B': Element would be inserted between A and D. Binary Search for 'F': Element would be inserted between D and G.
2. Sort<T>(T[], IComparer<T>) Method
This method Sorts the elements in an Array using the specified IComparer<T> generic interface.
Syntax:
public static void Sort<T>(T[] array, IComparer<T> comparer);
Parameter: Thie method takes to parameters
- T[] array: An array of elements of type T to be sorted
- ICOmparer<T>comparer: An object that implements the IComparer<T> interface, used to define the custom comparison logic for the array elements.
Return Type: This method does not return a value. it sorts the array in place.
Exceptions:
- ArgumentNullException: If the array is null.
- InvalidOperationException: If the comparer is null and there is no implementation of the IComparable<T> generic interface.
- ArgumentException: If the implementation of comparer caused an error during the sort.
Example: This example demonstrates how to sort an array in reverse order using cutrom compare and perform binary searches to find or determine the insertion point of specific elements.
// C# program to demonstrate the use of the
// Array.Sort<T>(T[], IComparer<T>) method
using System;
using System.Collections.Generic;
public class GeeK : IComparer<string>
{
public int Compare(string x, string y)
{
// Compare x and y in reverse order
// Reverse the order by swapping x and y
return y.CompareTo(x);
}
}
class Geeks
{
public static void Main()
{
// array elements
string[] arr = new string[5] { "A", "D", "X", "G", "M" };
foreach (string g in arr)
{
// display original array
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort: ");
GeeK gg = new GeeK();
// Sort<T>(T[], IComparer<T>) method
Array.Sort(arr, gg);
foreach (string g in arr)
{
// display sorted array
Console.WriteLine(g);
}
Console.WriteLine("\nD Sorts between :");
// binary Search for "D"
int index = Array.BinarySearch(arr, "D");
// call "sortT" function
sortT(arr, index);
Console.WriteLine("\nF Sorts between :");
index = Array.BinarySearch(arr, "F");
sortT(arr, index);
}
public static void sortT<T>(T[] arr, int index)
{
if (index < 0)
{
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("Not found. Sorts between: ");
if (index == 0)
Console.Write("Beginning of array and ");
else
Console.Write("{0} and ", arr[index - 1]);
if (index == arr.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", arr[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
Output
A D X G M After Sort: X M G D A D Sorts between : Not found. Sorts between: Beginning of array and X. F Sorts between : Not found. Sorts between: Beginning of array and X.
3. Array.Sort<T>(T[], Int32, Int32) Method
This method sorts a range of elements in an array, specified by the starting index(Int 32) and the length(Int32) of the range. It uses the IComparable<T> interface of each element in the array to perform the sorting.
Syntax:
public static void Sort<T>(T[] array, int index, int length);
Parameter: This method takes three parameters
- array(T[]): The array to be sorted
- index(Int32): The starting index of the range to sort.
- Length(Int32): he number of elements to sort, starting from the specified index.
Return Type: This method does not return a value. it sorts the array in place.
Exceptions:
- ArgumentNullException: If the array is null.
- ArgumentOutOfRangeException: If the index is less than the lower bound of array or length is less than zero.
- ArgumentException: If the index and length do not specify a valid range in the array.
- InvalidOperationException: If one or more elements in the array do not implement the IComparable<T> generic interface.
Example: This example demonstrates sorting a specified range of an array both in default and reverse order using Array.Sort with or without custom comparer.
// C# program to demonstrate the use of
// Array.Sort<T>(T[], Int32, Int32) method
using System;
using System.Collections.Generic;
public class Geek : IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order
return y.CompareTo(x);
}
}
public class Geeks
{
public static void Main()
{
// Array elements
string[] arr = { "AB", "CD", "GH", "EF", "MN", "IJ" };
Console.WriteLine("Original Array :");
Display(arr);
Console.WriteLine("\nSort the array between index 1 to 4");
// Array.Sort(T[], Int32, Int32) method
// Sort will happen between index 1 to 4
Array.Sort(arr, 1, 4);
Display(arr);
Console.WriteLine("\nSort the array reversely in between index 1 to 4");
// Sort will happen between index 1 to 4 reversely
Array.Sort(arr, 1, 4, new Geek());
Display(arr);
}
public static void Display(string[] arr)
{
foreach (string g in arr)
{
Console.WriteLine(g);
}
}
}
Output
Original Array : AB CD GH EF MN IJ Sort the array between index 1 to 4 AB CD EF GH MN IJ Sort the array reversely in between index 1 to 4 AB MN GH EF CD IJ
4. Array.Sort<T>(T[], Comparison<T>) Method
This method sorts the elements in an Array using the specified Comparison<T>.
Syntax:
Array.Sort<T>(T[] array, Comparison<T> comparison)
Parameters: This method takes two parameters
- array: The array of type T[] that you want to sort.
- Comparison<T> comparison: A Comparison<T> de;egate that defines the sort order. This delegate compares two elements of the array.
Return Type: This method does not return a value. it sorts the array in place.
Exceptions:
- ArgumentNullException: If the array is null or comparison is null.
- ArgumentException: If the implementation of comparison caused an error during the sort.
Example: This example demonstrates how to sort an array of strings using a custom comparison function that handles null values and compares non-null strings lexicographically.
// C# program to demonstrate the use of the
// Array.Sort<T>(T[ ], Comparison<T>) Method
using System;
using System.Collections.Generic;
class Geeks {
private static int CompareComp(string x, string y)
{
// Handle null values first
if (x == null && y == null) {
// If both x and y are null, they're equal
return 0;
} else if (x == null) {
// If x is null but y is not, y is greater
return 1;
} else if (y == null) {
// If y is null but x is not, x is greater
return -1;
} else {
// Compare non-null values
return string.Compare(x, y);
}
}
public static void Main()
{
string[] arr = { "Java", "C++", "Scala",
"C", "Ruby", "Python" };
Console.WriteLine("Original Array: ");
// display original array
Display(arr);
Console.WriteLine("\nSort with Comparison: ");
// Array.Sort<T>(T[], Comparison<T>)
// Method
Array.Sort(arr, CompareComp);
// display sorted array
Display(arr);
}
// Display function
public static void Display(string[] arr)
{
foreach (string g in arr)
{
Console.WriteLine(g);
}
}
}
Output
Original Array: Java C++ Scala C Ruby Python Sort with Comparison: C C++ Java Python Ruby Scala