How to Sort an Array in C# | Array.Sort() Method Set 1 (original) (raw)

Last Updated : 04 Feb, 2025

**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:

  1. **Sort(T[]) Method
  2. **Sort(T[], IComparer) Method
  3. **Sort(T[], Int32, Int32) Method
  4. **Sort(T[], Comparison) Method
  5. **Sort(Array, Int32, Int32, IComparer) Method
  6. **Sort(Array, Array, Int32, Int32, IComparer) Method
  7. **Sort(Array, Int32, Int32) Method
  8. **Sort(Array, Array, Int32, Int32) Method
  9. **Sort(Array, IComparer) Method
  10. **Sort(Array, Array, IComparer) Method
  11. **Sort(Array, Array) Method
  12. **Sort(Array) Method
  13. **Sort(T[], Int32, Int32, IComparer) Method
  14. **Sort<TKey,TValue>(TKey[], TValue[]) Method
  15. **Sort<TKey,TValue>(TKey[], TValue[], IComparer) Method
  16. **Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Method
  17. **Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer) Method

In this article, we will discuss the first 4 methods.

Sort an Array in C#

1. Sort(T[]) Method

This method sorts the elements in an Array using the **IComparable generic interface implementation of each element of the Array.

**Syntax:

Array.Sort(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 interface.

**Return Type: This method does not return a value. it sorts the array in place.

**Exceptions:

**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# `

// C# Program to demomstrates the use
// of the Array.Sort(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[], IComparer) Method

This method Sorts the elements in an Array using the specified **IComparer generic interface.

**Syntax:

public static void Sort(T[] array, IComparer comparer);

**Parameter: Thie method takes to parameters

**Return Type: This method does not return a value. it sorts the array in place.

**Exceptions:

**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# `

// C# program to demonstrate the use of the
// Array.Sort(T[], IComparer) method using System; using System.Collections.Generic;

public class GeeK : IComparer { 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[], 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 interface of each element in the array to perform the sorting.

**Syntax:

public static void Sort(T[] array, int index, int length);

**Parameter: This method takes three parameters

**Return Type: This method does not return a value. it sorts the array in place.

**Exceptions:

**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# `

// C# program to demonstrate the use of // Array.Sort(T[], Int32, Int32) method using System; using System.Collections.Generic;

public class Geek : IComparer { 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[], Comparison) Method

This method sorts the elements in an Array using the specified Comparison.

**Syntax:

Array.Sort(T[] array, Comparison comparison)

**Parameters: This method takes two parameters

**Return Type: This method does not return a value. it sorts the array in place.

**Exceptions:

**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# `

// C# program to demonstrate the use of the // Array.Sort(T[ ], Comparison) 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