How to sort an Array in C# | Array.Sort() Method | Set – 5

Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods:

  • 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

Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>) Method

This method sorts a pair of array objects based on the keys in the first array using the specified IComparer;T> generic interface. Here in the 2 arrays one contains the keys and the other contains the corresponding items.



Syntax: public static void Sort<TKey, TValue> (TKey[] keys, TValue[] items, IComparer comparer);
Here, TKey is the type of the elements of the key array and TValue the type of the elements of the items array.

Parameters:
keys: It is the one-dimensional array that contains the keys to sort.
items: It is the one-dimensional array that contains the items that correspond to the keys in keys.
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements.

Exceptions:

  • ArgumentNullException: If the keys is null.
  • ArgumentException: If the items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the length of keys is greater than the length of items.
  • InvalidOperationException: If comparer is null

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use of
// Array.Sort<TKey, TValue>(TKey[], 
// TValue[], IComparer<TKey>) Method
using System;
using System.Collections.Generic;
  
class compare : IComparer<string> {
  
    public int Compare(string x, string y)
    {
        // Compare x to y
        return x.CompareTo(y);
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Initialize two array
        String[] arr1 = { "H", "J", "K",
                   "L", "I", "N", "M" };
  
        String[] arr2 = { "A", "E", "D",
                   "C", "F", "B", "G" };
  
        // Instantiate the IComparer object
        compare g = new compare();
  
        // Display orginal values of the array
        Console.WriteLine("The original order of"
                    + " elements in the array:");
  
        Display(arr1, arr2);
  
        // Sort the array
        // "arr1" is keys array
        // "arr2" is items array
        // "g" is IComparer<TKey> object
        Array.Sort(arr1, arr2, g);
  
        Console.WriteLine("\nAfter Sorting: ");
        Display(arr1, arr2);
    }
  
    // Display function
    public static void Display(String[] arr1,
                               String[] arr2)
    {
        for (int i = 0; i < arr1.Length; i++)
        {
            Console.WriteLine(arr1[i] + " : " + arr2[i]);
        }
    }
}

chevron_right


Output:

The original order of elements in the array:
H : A
J : E
K : D
L : C
I : F
N : B
M : G

After Sorting: 
H : A
I : F
J : E
K : D
L : C
M : G
N : B

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32) Method

This method is used to sort a range of elements in a pair of array objects based on the keys in the first array. Here in the 2 arrays one contains the keys and the other contains the corresponding items.

Syntax: public static void Sort<TKey, TValue> (TKey[] keys, TValue[] items, IComparer comparer, int index, int len);
Here, TKey is the type of the elements of the key array and TValue is the type of the elements of the items array.

Parameters:
keys: It is the one-dimensional array that contains the keys to sort.
items: It is the one-dimensional array that contains the items that correspond to the keys in keys.
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements.
index: It is the starting index of the range to sort.
len: It is the number of elements in the range to sort.

Exceptions:

  • ArgumentNullException: If the keys is null.
  • ArgumentOutOfRangeException: If index is less than the lower bound of keys or len is less than zero.
  • ArgumentException: If the items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the len of keys is greater than the length of items or index and len do not specify a valid range in the keysArray or items is not null and index and len do not specify a valid range in the itemsArray.
  • InvalidOperationException: When one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Example:


filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use of
// Array.Sort<TKey, TValue>(TKey[], TValue[], 
// Int32, Int32) Method
using System;
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Initialize two array
        String[] arr1 = {"H", "J", "K",
                   "L", "I", "M", "N"};
  
        String[] arr2 = {"A", "E", "D",
                   "C", "F", "B", "G"};
  
        // Display orginal values of the array
        Console.WriteLine("The original order of"
                    + " elements in the array:");
  
        Display(arr1, arr2);
  
        // Sort the array
        // "arr1" is keys array
        // "arr2" is items array
        // start index 1
        // rang upto index 5
        Array.Sort(arr1, arr2, 1, 5);
  
        Console.WriteLine("\nAfter Sorting: ");
        Display(arr1, arr2);
    }
  
    // Display function
    public static void Display(String[] arr1, String[] arr2)
    {
        for (int i = 0; i < arr1.Length; i++) 
        {
            Console.WriteLine(arr1[i] + " : " + arr2[i]);
        }
    }
}

chevron_right


Output:

The original order of elements in the array:
H : A
J : E
K : D
L : C
I : F
M : B
N : G

After Sorting: 
H : A
I : F
J : E
K : D
L : C
M : B
N : G

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method

This method is used to sort a range of elements in a pair of array objects based on the keys in the first array using the specified IComparer<T> generic interface. Here in the 2 arrays one contains the keys and the other contains the corresponding items.

Syntax: public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int len, IComparer<TKey> comparer);

Parameters:
keys: It is the one-dimensional array that contains the keys to sort.
items: It is the one-dimensional array that contains the items that correspond to the keys in keys.
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements.
index: It is the starting index of the range to sort.
len: It is the number of elements in the range to sort.
comparer: It is the IComparer<T> generic interface implementation to use when comparing elements.

Exceptions:

  • ArgumentNullException: If the keys is null.
  • ArgumentOutOfRangeException: If the index is less than the lower bound of keys or len is less than zero.
  • ArgumentException: If items is not null and the lower bound of keys does not match the lower bound of items or items is not null and the len of keys is greater than the length of items or index and len do not specify a valid range in the keysArray or items is not null and index and len do not specify a valid range in the itemsArray or the implementation of comparer caused an error during the sort.
  • InvalidOperationException: When one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use of
// Array.Sort<TKey, TValue>(TKey[], TValue[],
// Int32, Int32, IComparer<TKey>) Method
using System;
using System.Collections.Generic;
  
class compare : IComparer<string> {
  
    public int Compare(string x, string y)
    {
        // Compare x to y
        return x.CompareTo(y);
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Initialize two array
        String[] arr1 = {"H", "J", "K",
                   "L", "I", "M", "N"};
  
        String[] arr2 = {"A", "E", "D",
                   "C", "F", "B", "G"};
  
        // Instantiate the IComparer object
        compare g = new compare();
  
        // Display orginal values of the array
        Console.WriteLine("The original order of"
                    + " elements in the array:");
  
        Display(arr1, arr2);
  
        // Sort the array
        // "arr1" is keys array
        // "arr2" is items array
        // "g" is IComparer<TKey> object
        // start index 1
        // rang upto index 5
        Array.Sort(arr1, arr2, 1, 5, g);
  
        Console.WriteLine("\nAfter Sorting: ");
        Display(arr1, arr2);
    }
  
    // Display function
    public static void Display(String[] arr1, String[] arr2)
    {
        for (int i = 0; i < arr1.Length; i++) 
        {
            Console.WriteLine(arr1[i] + " : " + arr2[i]);
        }
    }
}

chevron_right


Output:

The original order of elements in the array:
H : A
J : E
K : D
L : C
I : F
M : B
N : G

After Sorting: 
H : A
I : F
J : E
K : D
L : C
M : B
N : G

Reference:



My Personal Notes arrow_drop_up

3rd year student of Information Technology JADAVPUR UNIVERSITY

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.