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

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(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, Int32, Int32, IComparer) Method

This method sorts the elements in a range in a one-dimensional array using a specified IComparer.



Syntax: public static void Sort (Array arr, int start, int len, IComparer comparer);

Parameters:

“arr” :It is the one-dimensional array to sort.
“start” : 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 implementation to use when comparing elements or null to use the IComparable implementation of each element.

Exceptions:

  • ArgumentNullException: If the array is null.
  • RankException: If the array is multidimensional.
  • ArgumentOutOfRangeException if the start index is less than the lower bound of array or len is less than zero.
  • ArgumentException: If the start index and len does not specify a valid range in array or if the implementation of comparer caused an error during the sort.
  • InvalidOperationException: If comparer is null, and one or more elements in array do not implement the IComparable interface.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use 
// of  Array.Sort(Array, Int32, Int32, 
// IComparer) method
using System;
using System.Collections;
  
class comparer : IComparer {
  
    // Call CaseInsensitiveComparer.Compare
    public int Compare(Object x, Object y)
    {
        return (new CaseInsensitiveComparer()).Compare(x, y);
    }
}
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // initialize a array.
        string[] arr = {"ABC", "GHI", "JKL",
                       "DEF", "MNO", "XYZ"};
  
        // Instantiate the reverse comparer.
        IComparer g = new comparer();
  
        // Display original values of the array.
        Console.WriteLine("The original order of "+
                          "elements in the array:");
        Display(arr);
  
        // Sort a section of the array
        // using the IComparer object
        // sorting happens in the range
        // of index 1 to 4
        // "g" is IComparer object
        Array.Sort(arr, 1, 4, g);
          
        Console.WriteLine("\nAfter sorting in a range of"+
             " index 1 to 4 using the IComparer object:");
  
        Display(arr);
    }
  
    // Display function
    public static void Display(string[] arr)
    {
        for (int i = arr.GetLowerBound(0); 
        i <= arr.GetUpperBound(0); i++) {
  
            Console.WriteLine(arr[i]);
        }
    }
}

chevron_right


Output:

The original order of elements in the array:
ABC
GHI
JKL
DEF
MNO
XYZ

After sorting in a range of index 1 to 4 using the IComparer object:
ABC
DEF
GHI
JKL
MNO
XYZ

Sort(Array, Array, Int32, Int32, IComparer) Method

This method sorts a range of elements in a pair of one-dimensional array objects based on the keys in the first Array using the specified IComparer. Here the objects contain the keys and the corresponding items.

Syntax: public static void Sort (Array key, Array items, int start, int len, IComparer comparer);

Parameters:

key: It is the one-dimensional array which contains the keys to sort.
items: It is the one-dimensional array which contains the items that correspond to each of the keys in the keysArray(previous array).
start: 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 implementation to use when comparing elements or null to use the IComparable implementation of each element.


Exceptions:

  • ArgumentNullException: If the key is null.
  • RankException: If the keysArray is multidimensional.
  • ArgumentOutOfRangeException: If the start 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
    • If the items is not null, and the len of keys is greater than the length of items
    • If the start index and len do not specify a valid range in the keysArray.
    • If the items is not null, and start index and len do not specify a valid range in the itemsArray.
    • If the implementation of comparer caused an error during the sort.
  • InvalidOperationException: If the comparer is null.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use 
// of Array.Sort(Array, Array, Int32,
// Int32, IComparer) Method
using System;
using System.Collections;
  
class comparer : IComparer {
  
    // Call CaseInsensitiveComparer.Compare
    public int Compare(Object x, Object y)
    {
        return (new CaseInsensitiveComparer()).Compare(y, x);
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // initialize two Arrays
        String[] arr1 = {"H", "J", "K",
                   "L", "I", "N", "M"};
  
        String[] arr2 = {"A", "E", "D",
                   "C", "F", "B", "G"};
  
        // Instantiate the reverse comparer.
        IComparer g = new comparer();
  
        // Display original values of the array.
        Console.WriteLine("The original order of "+
                         "elements in the array:");
  
        Display(arr1, arr2);
  
        // Sort a section of the array 
        // using the IComparer object
        // sorting happens in the range
        // of index 1 to 4
        // "g" is IComparer object
        Array.Sort(arr1, arr2, 1, 4, g);
          
        Console.WriteLine("\nAfter sorting in a "+
                       "range of index 1 to 4 :");
  
        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 in a range of index 1 to 4 :
H : A
L : C
K : D
J : E
I : F
N : B
M : G

Sort(Array, Int32, Int32) Method

This method sorts the elements in a range in a one-dimensional array using the IComparable implementation of each element of the Array.

Syntax: public static void Sort (Array arr, int start, int len);

Parameters:

arr: It is the one-dimensional array to sort.
start: 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 array is null.
  • RankException: If the array is multidimensional.
  • ArgumentOutOfRangeException: If the start index is less than the lower bound of array or len is less than zero.
  • ArgumentException: If the start index and len does not specify a valid range in array.
  • InvalidOperationException: If the one or more elements in array do not implement the IComparable interface.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use of
// Array.Sort(Array, Int32, Int32) method
using System;
using System.Collections;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // initialize a array.
        string[] arr = {"ABC", "GHI", "JKL",
                       "DEF", "MNO", "XYZ"};
  
        // Display original values of the array.
        Console.WriteLine("The original order of"+
                       " elements in the array:");
  
        Display(arr);
  
        // sorting happens in the
        // range of index 1 to 4
        Array.Sort(arr, 1, 4);
  
        Console.WriteLine("\nAfter sorting in a range of "+
               "index 1 to 4 using the IComparer object:");
  
        Display(arr);
    }
  
    // Display function
    public static void Display(string[] arr)
    {
        for (int i = arr.GetLowerBound(0); 
        i <= arr.GetUpperBound(0); i++) {
  
            Console.WriteLine(arr[i]);
        }
    }
}

chevron_right


Output:


The original order of elements in the array:
ABC
GHI
JKL
DEF
MNO
XYZ

After sorting in a range of index 1 to 4 using the IComparer object:
ABC
DEF
GHI
JKL
MNO
XYZ

Sort(Array, Array, Int32, Int32) Method

This method sorts a range of elements in a pair of one-dimensional Array objects based on the keys in the first Array using the specified IComparer. Here the objects contain the keys and the corresponding items.

Syntax: public static void Sort (Array keys, Array items, int start, int len);

Parameters:

key: It is the one-dimensional array which contains the keys to sort.
items: It is the one-dimensional array which contains the items that correspond to each of the keys in the keysArray(previous array).
start: 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 key is null.
  • RankException: If the keysArray is multidimensional or the itemsArray is multidimensional.
  • ArgumentOutOfRangeException: If the start index is less than the lower bound of keys or len is less than zero.
  • ArgumentException:
    • If the items is not null, and the len of keys is greater than the length of items.
    • If the start index and len do not specify a valid range in the keysArray.
    • If the items is not null, and start index and len do not specify a valid range in the itemsArray.
    • If the implementation of comparer caused an error during the sort.
  • InvalidOperationException: If one or more elements in the keysArray do not implement the IComparable interface.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate the use of
// Array.Sort(Array, Int32, Int32, 
// IComparer) method
using System;
using System.Collections;
  
class comparer : IComparer {
  
    // Call CaseInsensitiveComparer.Compare
    public int Compare(Object x, Object y)
    {
        return (new CaseInsensitiveComparer()).Compare(y, x);
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    public static void Main()
    {
        // initialize two arrays
        String[] arr1 = {"H", "J", "K"
                   "L", "I", "N", "M"};
  
        String[] arr2 = {"A", "E", "D",
                   "C", "F", "B", "G"};
  
        // Display original values of the array.
        Console.WriteLine("The original order of elements in the array:");
        Display(arr1, arr2);
  
        // sorting happens in the range of index 1 to 4
        Array.Sort(arr1, arr2, 1, 4);
  
        Console.WriteLine("\nAfter sorting in a "+
                       "range of index 1 to 4 :");
  
        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 in a range of index 1 to 4 :
H : A
I : F
J : E
K : D
L : C
N : B
M : G

Reference:



My Personal Notes arrow_drop_up

2nd 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.