Tutorialspoint.dev

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

Array.Sort Method 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>(T[]) Method
  2. Sort<T>(T[], IComparer<T>) Method
  3. Sort<T>(T[], Int32, Int32) Method
  4. Sort<T>(T[], Comparison<T>) 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>(T[], Int32, Int32, IComparer<T>) Method
  14. Sort<TKey,TValue>(TKey[], TValue[]) Method
  15. Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Method
  16. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Method
  17. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Method

Here we will discuss the first 4 methods.



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: public static void Sort (T[] array);

Parameter:
array: It is the one dimensional, zero-based Array which is to be sorted.

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:

// C# Program to illustrate the use 
// of the Array.Sort<T>(T[]) Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // array elements
        string[] arr = new string[5] { "A"
                      "D", "X", "G", "M" };
  
        foreach(string g in arr)
        {
            Console.WriteLine(g);
            // display original array
        }
  
        Console.WriteLine(" After Sort:");
        Array.Sort(arr);
  
        foreach(string g in arr)
        {
            Console.WriteLine(g);
            // display sorted array
        }
  
        Console.WriteLine(" B sorts between :");
  
        // binary Search for "B"
        int index = Array.BinarySearch(arr, "B");
  
        // call "sortT" function
        // which is the Sort<T>(T[]) function
        sortT(arr, index);
          
        Console.WriteLine(" F sorts between :");
        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 in the array.
        if (index < 0) {
              
            index = ~index;
  
            if (index == 0)
                Console.Write("beginning of array");
            else
                Console.Write("{0} and ", arr[index - 1]);
  
            if (index == arr.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}", arr[index]);
        }
    }
}

Output:

A
D
X
G
M

After Sort:
A
D
G
M
X

B sorts between :
A and D

F sorts between :
D and G

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, System.Collections.Generic.IComparer<T> comparer);

Parameters:

  • T : It is the type of the elements of the array.
  • array : It is the one-dimensional Array which is to be sorted.
  • comparer : It is the IComparer<T> generic interface implementation to use when comparing elements or null to use the IComparable<T> generic interface implementation of each element.

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:

// C# progrm 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.
        return x.CompareTo(y);
    }
}
  
class GFG {
  
    // Main Method
    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(" After 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(" D Sorts between :");
  
        // binary Search for "D"
        int index = Array.BinarySearch(arr, "D");
          
         // call "sortT" function
        sortT(arr, index);
         
        Console.WriteLine(" F 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: 
A
D
G
M
X

D Sorts between :
Found at index 1.

F Sorts between :
Not found. Sorts between: D and G.

Array.Sort<T>(T[], Int32, Int32) Method

This method sorts the elements in a range of in an Array using the IComparable<T> generic interface implementation of each element of the Array.

Syntax: public static void Sort<T> (T[] array, int index, int length);

Parameters:

  • array: It is the one-dimensional, zero-based Array to sort.
  • index: It is the starting index of the range to sort.
  • length: It is the number of elements in the range to sort.

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:

// 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 Example {
  
    // Main Method
    public static void Main()
    {
        // Array elements
        string[] arr = {"AB", "CD"
           "GH", "EF", "MN", "IJ"};
             
        Console.WriteLine("Original Array :");
          
        Display(arr);
  
        Console.WriteLine(" Sort the array between "+
                                      "index 1 to 4");
          
        // Array.Sort(T[], Int32, Int32) method
        // sort will happen in between
        // index 1 to 4
        Array.Sort(arr, 1, 4);
        Display(arr);
  
        Console.WriteLine(" Sort the array reversely"+
                           " in between index 1 to 4");
          
        // sort will happen in 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

Array.Sort<T>(T[], Comparison<T>) Method

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

Syntax: public static void Sort<T> (T[] array, Comparison<T> comparison);



Parameters:

  • array: It is the one-dimensional zero-based Array which is to be sorted.
  • comparison: It is the comparison<T> to used when comparing elements.

Exceptions:

  • ArgumentNullException: If the array is null or comparison is null.
  • ArgumentException: If the implementation of comparison caused an error during the sort.

Example:

// C# program to demonstrate the use of the 
// Array.Sort<T>(T[ ], Comparison<T>) Method
using System;
using System.Collections.Generic;
  
class GFG {
      
    private static int CompareComp(string x, string y)
    {
        if (y == null && x == null) {
              
            // If x and y is null
            // then x and y are same
            return 0;
        }
        else {
              
            // If x is null but y is not 
            // null then y is greater.
            return -1;
        }
    }
  
    // Main method
    public static void Main()
    {
        string[] arr = {"Java", "C++", "Scala",
                        "C", "Ruby", "Python"};
        
        Console.WriteLine("Original Array: ");
          
        // display original array
        Display(arr);
          
        Console.WriteLine(" Sort 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: 
Python
Ruby
C
Scala
C++
Java

Reference:



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter