C# Array.Sort and Span.Sort
last modified November 15, 2026
In this article we sort arrays and spans with the built-in
Array.Sort and MemoryExtensions.Sort methods. We sort
whole arrays and ranges, use custom comparers, sort two arrays together, and
show that the sort is not stable.
Sorting is arranging the elements of a collection in a specific order, for instance from the smallest to the largest. A sorting algorithm is the sequence of steps that produces this order.
Array.Sort
The Array.Sort method sorts an array in place. It has more than
a dozen overloads: generic and non-generic, with a range, with a
Comparison<T> delegate or an IComparer<T>,
and with a second array of items that follows the keys. The span-based
Sort extension methods from MemoryExtensions offer the
same options for Span<T>.
| Property | Value |
|---|---|
| Algorithm | introsort (quicksort, heap sort, insertion sort) |
| Average and worst case | O(n log n) |
| Extra memory | O(log n) for recursion, sorts in place |
| Stable | no |
List<T>.Sort calls Array.Sort on the list's
internal array, so everything in this article applies to lists too. How the
algorithm works is explained in the introsort
article.
C# Array.Sort example
The first example sorts integers, strings and doubles in ascending order.
int[] nums = [7, -3, 12, 0, 5, -8, 1];
Array.Sort(nums);
Console.WriteLine(string.Join(" ", nums));
string[] words = ["sky", "Apple", "cup", "banana", "War", "atom"];
Array.Sort(words);
Console.WriteLine(string.Join(" ", words));
Array.Sort(words, StringComparer.Ordinal);
Console.WriteLine(string.Join(" ", words));
double[] vals = [2.5, double.NaN, -1.0, 0.0, double.NegativeInfinity];
Array.Sort(vals);
Console.WriteLine(string.Join(" ", vals));
Without a comparer, the elements are compared with their default comparer,
which uses the IComparable<T> implementation of the type.
Array.Sort(words);
The default comparison of strings is culture-sensitive: lowercase and uppercase letters are sorted together, so Apple comes before atom and War is last.
Array.Sort(words, StringComparer.Ordinal);
The ordinal comparer compares the numeric values of the characters. All uppercase letters come before lowercase ones.
double[] vals = [2.5, double.NaN, -1.0, 0.0, double.NegativeInfinity];
For floating-point numbers, NaN is placed before all other
values, including negative infinity.
$ dotnet run -8 -3 0 1 5 7 12 Apple atom banana cup sky War Apple War atom banana cup sky NaN -∞ -1 0 2.5
Sorting a range and descending order
We can sort only a part of an array and sort in descending order.
int[] nums = [9, 4, 7, 1, 8, 2, 6, 3, 5];
Array.Sort(nums, 2, 5);
Console.WriteLine(string.Join(" ", nums));
int[] vals = [9, 4, 7, 1, 8, 2, 6, 3, 5];
Array.Sort(vals);
Array.Reverse(vals);
Console.WriteLine(string.Join(" ", vals));
int[] data = [9, 4, 7, 1, 8, 2, 6, 3, 5];
Array.Sort(data, (a, b) => b.CompareTo(a));
Console.WriteLine(string.Join(" ", data));
int[] items = [9, 4, 7, 1, 8, 2, 6, 3, 5];
Array.Sort(items, 0, 4, Comparer<int>.Create((a, b) => b.CompareTo(a)));
Console.WriteLine(string.Join(" ", items));
There is no descending flag; we either reverse the sorted array or pass a comparison that reverses the order.
Array.Sort(nums, 2, 5);
The overload takes the starting index and the number of elements. Only the five elements from index 2 are sorted: 7, 1, 8, 2 and 6. The rest of the array is untouched.
Array.Sort(vals); Array.Reverse(vals);
Sorting and then reversing is the fastest way to get a descending order of primitive values, because the sort can use its specialized code for the default comparer.
Array.Sort(data, (a, b) => b.CompareTo(a));
A Comparison<T> lambda with swapped arguments sorts in
descending order. Avoid writing -a.CompareTo(b) or
b - a; the latter overflows for large values.
Array.Sort(items, 0, 4, Comparer<int>.Create((a, b) => b.CompareTo(a)));
The range overloads take an IComparer<T>, not a
Comparison<T>. The Comparer<T>.Create
method wraps a delegate into a comparer.
$ dotnet run 9 4 1 2 6 7 8 3 5 9 8 7 6 5 4 3 2 1 9 8 7 6 5 4 3 2 1 9 7 4 1 8 2 6 3 5
Sorting objects
There are three ways to tell Array.Sort how to order objects:
implement IComparable<T> in the type, pass a
Comparison<T> delegate, or pass an
IComparer<T> object.
User[] users =
[
new("Paul", "Novak", 34),
new("Lucia", "Smith", 27),
new("Robert", "Brown", 41),
new("Anna", "Novak", 22),
new("Peter", "Black", 27),
];
Array.Sort(users);
Print("IComparable (by last name, first name):", users);
Array.Sort(users, (a, b) => a.Age.CompareTo(b.Age));
Print("Comparison (by age):", users);
Array.Sort(users, new FirstNameLengthComparer());
Print("IComparer (by first name length):", users);
static void Print(string title, User[] users)
{
Console.WriteLine(title);
foreach (var u in users)
{
Console.WriteLine($" {u.FirstName} {u.LastName}, {u.Age}");
}
}
record User(string FirstName, string LastName, int Age) : IComparable<User>
{
public int CompareTo(User? other)
{
if (other is null) return 1;
int res = string.Compare(LastName, other.LastName, StringComparison.Ordinal);
return res != 0 ? res : string.Compare(FirstName, other.FirstName, StringComparison.Ordinal);
}
}
class FirstNameLengthComparer : IComparer<User>
{
public int Compare(User? x, User? y) => x!.FirstName.Length.CompareTo(y!.FirstName.Length);
}
The User record defines its natural order: by last name, then by
first name.
int res = string.Compare(LastName, other.LastName, StringComparison.Ordinal); return res != 0 ? res : string.Compare(FirstName, other.FirstName, StringComparison.Ordinal);
If the last names are equal, the first names decide. Without a comparer,
Array.Sort uses this method. If the type implemented no
IComparable interface, the sort would throw an
InvalidOperationException.
Array.Sort(users, (a, b) => a.Age.CompareTo(b.Age));
A lambda defines an ad hoc order without changing the type.
class FirstNameLengthComparer : IComparer<User>
{
public int Compare(User? x, User? y) => x!.FirstName.Length.CompareTo(y!.FirstName.Length);
}
A comparer class is reusable and can hold state, for example a culture or a sort direction.
$ dotnet run IComparable (by last name, first name): Peter Black, 27 Robert Brown, 41 Anna Novak, 22 Paul Novak, 34 Lucia Smith, 27 Comparison (by age): Anna Novak, 22 Peter Black, 27 Lucia Smith, 27 Paul Novak, 34 Robert Brown, 41 IComparer (by first name length): Anna Novak, 22 Paul Novak, 34 Peter Black, 27 Lucia Smith, 27 Robert Brown, 41
Sorting keys and items
The Array.Sort(keys, items) overload sorts two arrays at once. The
first array holds the keys; each element of the second array moves together
with its key.
string[] names = ["Paul", "Lucia", "Robert", "Anna", "Peter"];
int[] ages = [34, 27, 41, 22, 30];
Array.Sort(ages, names);
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{names[i],-7} {ages[i]}");
}
Console.WriteLine();
string[] files = ["report.pdf", "notes.txt", "photo.jpg", "data.csv"];
long[] sizes = [524_288, 1_200, 2_097_152, 48_000];
Array.Sort(sizes, files, Comparer<long>.Create((a, b) => b.CompareTo(a)));
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine($"{files[i],-11} {sizes[i],10:N0}");
}
We sort names by ages and file names by file sizes.
Array.Sort(ages, names);
The ages array is sorted and the names array is
rearranged in the same way. This is useful for parallel arrays, which are
common in numeric code and in data read from columns.
Array.Sort(sizes, files, Comparer<long>.Create((a, b) => b.CompareTo(a)));
The comparer applies to the keys. The files are listed from the largest to the smallest.
$ dotnet run Anna 22 Lucia 27 Peter 30 Paul 34 Robert 41 photo.jpg 2,097,152 report.pdf 524,288 data.csv 48,000 notes.txt 1,200
Span.Sort
The MemoryExtensions class defines Sort extension
methods for Span<T>. They sort any contiguous memory: a
part of an array, stack memory, or a slice of a list obtained with
CollectionsMarshal.AsSpan.
Span<int> span = stackalloc int[] { 8, 3, 9, 1, 7, 2 };
span.Sort();
Console.WriteLine(string.Join(" ", span.ToArray()));
int[] nums = [50, 40, 30, 20, 10, 5, 4, 3, 2, 1];
nums.AsSpan(2, 5).Sort();
Console.WriteLine(string.Join(" ", nums));
nums.AsSpan()[..4].Sort();
Console.WriteLine(string.Join(" ", nums));
Span<string> words = ["sky", "cup", "forest", "war"];
words.Sort((a, b) => a.Length.CompareTo(b.Length));
Console.WriteLine(string.Join(" ", words.ToArray()));
Span<int> keys = [3, 1, 2];
Span<char> items = ['c', 'a', 'b'];
keys.Sort(items);
Console.WriteLine($"{string.Join(" ", keys.ToArray())} | {string.Join(" ", items.ToArray())}");
A span sort does not allocate and does not need index and length arguments; the slice defines the range.
Span<int> span = stackalloc int[] { 8, 3, 9, 1, 7, 2 };
span.Sort();
We sort numbers allocated on the stack.
nums.AsSpan(2, 5).Sort();
This sorts the same range as Array.Sort(nums, 2, 5).
nums.AsSpan()[..4].Sort();
A range expression selects the first four elements.
words.Sort((a, b) => a.Length.CompareTo(b.Length));
The span overloads accept a Comparison<T> directly.
keys.Sort(items);
The keys and items overload works with two spans of the same length.
$ dotnet run 1 2 3 7 8 9 50 40 4 5 10 20 30 3 2 1 4 5 40 50 10 20 30 3 2 1 sky cup war forest 1 2 3 | a b c
Array.Sort is not stable
A sort is stable if equal elements keep their original relative
order. Array.Sort is not stable. LINQ's OrderBy is.
var rnd = new Random(3);
string[] names = ["Ann", "Bob", "Cid", "Dan", "Eve", "Fay", "Gus", "Hal", "Ivy", "Jon"];
Student[] students = [.. Enumerable.Range(0, 20)
.Select(i => new Student($"{names[i % 10]}{i / 10 + 1}", rnd.Next(1, 4)))];
Student[] a = [.. students];
Array.Sort(a, (x, y) => x.Grade.CompareTo(y.Grade));
Student[] b = [.. students.OrderBy(s => s.Grade)];
Console.WriteLine("input: " + string.Join(" ", students.Where(s => s.Grade == 1).Select(s => s.Name)));
Console.WriteLine("Array.Sort: " + string.Join(" ", a.Where(s => s.Grade == 1).Select(s => s.Name)));
Console.WriteLine("OrderBy: " + string.Join(" ", b.Where(s => s.Grade == 1).Select(s => s.Name)));
Student[] c = [.. students.Take(16)];
Array.Sort(c, (x, y) => x.Grade.CompareTo(y.Grade));
Console.WriteLine("16 items: " + string.Join(" ", c.Where(s => s.Grade == 1).Select(s => s.Name)));
record Student(string Name, int Grade);
We generate 20 students with random grades from 1 to 3, sort them by grade with both methods, and print the students with grade 1.
Array.Sort(a, (x, y) => x.Grade.CompareTo(y.Grade));
After Array.Sort, the students with the same grade are in a
different order than in the input.
Student[] b = [.. students.OrderBy(s => s.Grade)];
OrderBy keeps the input order of equal elements.
Student[] c = [.. students.Take(16)];
Arrays with up to 16 elements are sorted with insertion sort, which is stable. The instability therefore shows only on larger inputs, and tests with small arrays do not reveal it. See stable sorting for ways to get a stable order.
$ dotnet run input: Ann1 Dan1 Fay1 Gus1 Dan2 Eve2 Gus2 Array.Sort: Ann1 Gus2 Eve2 Dan1 Dan2 Fay1 Gus1 OrderBy: Ann1 Dan1 Fay1 Gus1 Dan2 Eve2 Gus2 16 items: Ann1 Dan1 Fay1 Gus1 Dan2 Eve2
Performance of the overloads
The last example sorts one million random integers in different ways and prints the best time of five runs.
#:property PublishAot=false
using System.Diagnostics;
var rnd = new Random(17);
int[] data = [.. Enumerable.Range(0, 1_000_000).Select(_ => rnd.Next())];
Measure("Array.Sort(int[])", a => Array.Sort(a));
Measure("Span.Sort()", a => a.AsSpan().Sort());
Measure("Comparison<int>", a => Array.Sort(a, (x, y) => x.CompareTo(y)));
Measure("Comparer.Default", a => Array.Sort(a, Comparer<int>.Default));
Measure("Comparer.Create", a => Array.Sort(a, Comparer<int>.Create((x, y) => x.CompareTo(y))));
Measure("List.Sort()", a => new List<int>(a).Sort());
Measure("LINQ Order()", a => a.Order().ToArray());
Measure("LINQ OrderBy()", a => a.OrderBy(x => x).ToArray());
void Measure(string name, Action<int[]> sort)
{
long best = long.MaxValue;
for (int i = 0; i < 5; i++)
{
int[] copy = [.. data];
var sw = Stopwatch.StartNew();
sort(copy);
best = Math.Min(best, sw.ElapsedMilliseconds);
}
Console.WriteLine($"{name,-18} {best,4} ms");
}
Each sort gets a fresh copy of the same data.
Measure("Comparer.Default", a => Array.Sort(a, Comparer<int>.Default));
Measure("Comparer.Create", a => Array.Sort(a, Comparer<int>.Create((x, y) => x.CompareTo(y))));
Array.Sort recognizes the default comparer and uses its fast
path, which compares primitive values directly. A custom comparer is called
through an interface for every comparison.
Measure("LINQ Order()", a => a.Order().ToArray());
Measure("LINQ OrderBy()", a => a.OrderBy(x => x).ToArray());
Order on primitive values with the default comparer skips the
stable sort, because equal integers cannot be told apart.
OrderBy with a key selector builds a key array and an index
array and sorts stably, which is more than two times slower.
The sort with the default comparer, the span sort, the list sort and
Order take the same time. A Comparison delegate adds
about 30 percent and a comparer object created with
Comparer.Create nearly doubles the time.
$ dotnet run -c Release benchmark.cs Array.Sort(int[]) 59 ms Span.Sort() 59 ms Comparison<int> 76 ms Comparer.Default 59 ms Comparer.Create 110 ms List.Sort() 59 ms LINQ Order() 59 ms LINQ OrderBy() 149 ms
Source
Array.Sort method
MemoryExtensions.Sort method
In this article we have sorted arrays and spans with Array.Sort
and Span.Sort. For lists, see sort
List.
Other sorting articles in C#:
- Bubble sort
- Selection sort
- Insertion sort
- Shell sort
- Merge sort
- Quick sort
- Heap sort
- Counting sort
- Radix sort
- Bucket sort
- Stable sorting
- Binary search
- Introsort
- Quickselect
- External sort
- Timsort
Author
List all C# tutorials.