How to sort an Array in C# | Array.Sort() Method Set – 2
Last Updated :
06 Mar, 2019
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:
csharp
// 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]);
}
}
}
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:
csharp
// 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]);
}
}
}
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:
csharp
// 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]);
}
}
}
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:
csharp
// 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]);
}
}
}
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:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read