How to Sort an Array in C# | Array.Sort() Method Set - 1
Last Updated :
04 Feb, 2025
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[]) Method
- Sort<T>(T[], IComparer<T>) Method
- Sort<T>(T[], Int32, Int32) Method
- Sort<T>(T[], Comparison<T>) Method
- 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, IComparer) Method
- Sort(Array, Array, IComparer) Method
- Sort(Array, Array) Method
- Sort(Array) Method
- Sort<T>(T[], Int32, Int32, IComparer<T>) Method
- Sort<TKey,TValue>(TKey[], TValue[]) Method
- 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
In this article, we will discuss the first 4 methods.
Sort an Array in C#
1. 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:
Array.Sort<T>(T[] array);
Parameter: T[] array is a one-dimensional array of type T that you want to sort, T can be any type that implements the IComperable<T> interface.
Return Type: This method does not return a value. it sorts the array in place.
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: This example demonstrates how to sort an array, perform a binary search for specific elements and determine their potential insertion positions in a sorted array.
C#
// C# Program to demomstrates the use
// of the Array.Sort<T>(T[]) Method
using System;
class Geeks
{
public static void Main()
{
// array elements
string[] arr = new string[5] { "A", "D", "X", "G", "M" };
// Display original array
Console.WriteLine("Original Array:");
foreach (string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort:");
// Sorting the array
Array.Sort(arr);
// Display sorted array
foreach (string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinary Search for 'B':");
// Binary Search for "B"
int index = Array.BinarySearch(arr, "B");
sortT(arr, index);
Console.WriteLine("\nBinary Search for 'F':");
// Binary Search for "F"
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
if (index < 0)
{
// Convert to the actual index of
// the next larger element
index = ~index;
if (index == 0)
Console.WriteLine("Element would be inserted at the beginning of the array.");
else
Console.WriteLine($"Element would be inserted between {arr[index - 1]} and {arr[index]}.");
if (index == arr.Length)
Console.WriteLine("Element would be inserted at the end of the array.");
}
else
{
Console.WriteLine($"Element 'B' or 'F' found at index {index}.");
}
}
}
OutputOriginal Array:
A
D
X
G
M
After Sort:
A
D
G
M
X
Binary Search for 'B':
Element would be inserted between A and D.
Binary Search for 'F':
Element would be inserted between D and G.
2. 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, IComparer<T> comparer);
Parameter: Thie method takes to parameters
- T[] array: An array of elements of type T to be sorted
- ICOmparer<T>comparer: An object that implements the IComparer<T> interface, used to define the custom comparison logic for the array elements.
Return Type: This method does not return a value. it sorts the array in place.
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: This example demonstrates how to sort an array in reverse order using cutrom compare and perform binary searches to find or determine the insertion point of specific elements.
C#
// C# program 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
// Reverse the order by swapping x and y
return y.CompareTo(x);
}
}
class Geeks
{
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("\nAfter 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("\nD Sorts between :");
// binary Search for "D"
int index = Array.BinarySearch(arr, "D");
// call "sortT" function
sortT(arr, index);
Console.WriteLine("\nF 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);
}
}
}
OutputA
D
X
G
M
After Sort:
X
M
G
D
A
D Sorts between :
Not found. Sorts between: Beginning of array and X.
F Sorts between :
Not found. Sorts between: Beginning of array and X.
3. Array.Sort<T>(T[], Int32, Int32) Method
This method sorts a range of elements in an array, specified by the starting index(Int 32) and the length(Int32) of the range. It uses the IComparable<T> interface of each element in the array to perform the sorting.
Syntax:
public static void Sort<T>(T[] array, int index, int length);
Parameter: This method takes three parameters
- array(T[]): The array to be sorted
- index(Int32): The starting index of the range to sort.
- Length(Int32): he number of elements to sort, starting from the specified index.
Return Type: This method does not return a value. it sorts the array in place.
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: This example demonstrates sorting a specified range of an array both in default and reverse order using Array.Sort with or without custom comparer.
C#
// 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 Geeks
{
public static void Main()
{
// Array elements
string[] arr = { "AB", "CD", "GH", "EF", "MN", "IJ" };
Console.WriteLine("Original Array :");
Display(arr);
Console.WriteLine("\nSort the array between index 1 to 4");
// Array.Sort(T[], Int32, Int32) method
// Sort will happen between index 1 to 4
Array.Sort(arr, 1, 4);
Display(arr);
Console.WriteLine("\nSort the array reversely in between index 1 to 4");
// Sort will happen 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);
}
}
}
OutputOriginal 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
4. Array.Sort<T>(T[], Comparison<T>) Method
This method sorts the elements in an Array using the specified Comparison<T>.
Syntax:
Array.Sort<T>(T[] array, Comparison<T> comparison)
Parameters: This method takes two parameters
- array: The array of type T[] that you want to sort.
- Comparison<T> comparison: A Comparison<T> de;egate that defines the sort order. This delegate compares two elements of the array.
Return Type: This method does not return a value. it sorts the array in place.
Exceptions:
- ArgumentNullException: If the array is null or comparison is null.
- ArgumentException: If the implementation of comparison caused an error during the sort.
Example: This example demonstrates how to sort an array of strings using a custom comparison function that handles null values and compares non-null strings lexicographically.
C#
// C# program to demonstrate the use of the
// Array.Sort<T>(T[ ], Comparison<T>) Method
using System;
using System.Collections.Generic;
class Geeks {
private static int CompareComp(string x, string y)
{
// Handle null values first
if (x == null && y == null) {
// If both x and y are null, they're equal
return 0;
} else if (x == null) {
// If x is null but y is not, y is greater
return 1;
} else if (y == null) {
// If y is null but x is not, x is greater
return -1;
} else {
// Compare non-null values
return string.Compare(x, y);
}
}
public static void Main()
{
string[] arr = { "Java", "C++", "Scala",
"C", "Ruby", "Python" };
Console.WriteLine("Original Array: ");
// display original array
Display(arr);
Console.WriteLine("\nSort 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);
}
}
}
OutputOriginal Array:
Java
C++
Scala
C
Ruby
Python
Sort with Comparison:
C
C++
Java
Python
Ruby
Scala
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.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 find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers