How to sort an Array in C# | Array.Sort() Method | Set – 4
Last Updated :
13 Sep, 2021
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) Method
This method sorts the elements in an entire one-dimensional array using the IComparable implementation of each element of the Array.
Syntax: public static void Sort (Array arr);
Parameter:
arr: It is the one-dimensional array which is to be sorted.
Exceptions:
- ArgumentNullException: If the array null.
- RankException: If the array is multidimensional.
- InvalidOperationException: If one or more elements in array do not implement the IComparable interface.
Example:
csharp
// C# program to demonstrate the
// Array.Sort(Array) method
using System;
class GFG {
// Main Method
public static void Main()
{
// Initialize two array.
string[] arr = {"A", "E", "D",
"C", "F", "B", "G"};
// Display original values of the array
Console.WriteLine("The original array:");
Display(arr);
// Sort the array using two array
Array.Sort(arr);
Console.WriteLine("\n\nAfter sorting :");
Display(arr);
}
// Display function
public static void Display(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
}
}
Output: The original array:
A E D C F B G
After sorting :
A B C D E F G
Sort<T>(T[], Int32, Int32, IComparer<T>) Method
This method sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.
Syntax: public static void Sort<T> (T[] arr, int start, int len, IComparer<T> comparer);
Here T is the type of the elements of the array.
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<T> generic interface implementation to use when comparing elements.
Exceptions:
- ArgumentNullException: If the array is null.
- ArgumentOutOfRangeException: If the start index is less than the lower bound of array or length len is less than zero.
- ArgumentException: If start index and length len do not specify a valid range in array or the implementation of comparer caused an error during the sort.
- InvalidOperationException: If comparer is null.
Example:
csharp
// C# program to demonstrate the use of
// Sort<T>(T[], Int32, Int32, IComparer<T>)
// 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);
}
}
class GFG {
// Main Method
public static void Main()
{
// Initializing array
String[] arr = {"A", "D", "B",
"E", "C", "F", "G"};
// Instantiate the IComparer object
compare cmp = new compare();
// Display the original values of the array
Console.WriteLine("The original array:");
display(arr);
// sorting range is index 1 to 4
// "cmp" is the IComparer<T> object
Array.Sort(arr, 1, 4, cmp);
Console.WriteLine("\nAfter sorting the array using the IComparer:");
display(arr);
}
// display function
public static void display(String[] arr)
{
foreach(String a in arr)
Console.WriteLine(a);
}
}
Output: The original array:
A
D
B
E
C
F
G
After sorting the array using the IComparer:
A
B
C
D
E
F
G
Sort<TKey, TValue>(TKey[], TValue[]) Method
This method sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.
Syntax: public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items);
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.
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 one or more elements in the keys array do not implement the IComparable<T> generic interface.
Example:
csharp
// C# program to demonstrate the use of
// Array.Sort<TKey, TValue>(TKey[], TValue[])
// 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 original 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<T> 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]);
}
}
}
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
Similar Reads
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
9 min read
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[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to sort an Array in C# | Array.Sort() Method Set â 3 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, IComparer) Method Sort(Array, Array, IComparer) Method Sort(Array, Array) Method Sort(Array, IComparer) Method This
6 min read
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 This method sorts a pair of array objects based on the
7 min read
How to sort a list in C# | List.Sort() Method Set -2 List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of th
5 min read
How to sort a list in C# | List.Sort() Method Set -1 List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of th
5 min read
How to use Array.BinarySearch() Method in C# | Set -2 Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the
12 min read
How to sort an array in a single loop? Given an array of size N, the task is to sort this array using a single loop.How the array is sorted usually? There are many ways by which the array can be sorted in ascending order, like: Selection SortBinary SortMerge SortRadix SortInsertion Sort, etc In any of these methods, more than 1 loops is
12 min read
C# | How to insert an element in an Array? An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C#. Let's say we have an array and we want to insert an element at a specific position in this array. Here's how to do it. First get the element to be inserte
2 min read
C# | Copying the SortedList elements to an Array Object SortedList.CopyTo(Array, Int32) Method is used to copy SortedList elements to a one-dimensional Array object, starting at the specified index in the array. Syntax: public virtual void CopyTo (Array array, int arrayIndex); Parameters: array: It is the one-dimensional Array object that is the destinat
2 min read