C# Heap Sort
last modified November 6, 2026
In this article we implement the heap sort algorithm in C#. We build a max-heap
in an array, trace the sorting step by step, write a generic version, and use
the built-in PriorityQueue class, which is also a heap.
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.
Heap sort algorithm
A binary heap is a complete binary tree in which every parent is
greater than or equal to its children; this is a max-heap. The
largest element is in the root. A heap is stored in an array without any
pointers: the children of the element at index i are at
2i + 1 and 2i + 2.
Heap sort first rearranges the array into a max-heap. Then it repeatedly swaps the root with the last element of the heap, shrinks the heap by one, and restores the heap property by sifting down the new root. The largest elements collect at the end of the array.
| Property | Value |
|---|---|
| Best, average and worst case | O(n log n) |
| Extra memory | O(1), sorts in place |
| Stable | no |
Heap sort has a guaranteed O(n log n) running time and needs no extra memory.
In practice it is slower than quicksort, because it jumps around the array and
makes poor use of the CPU cache. The introsort algorithm behind
Array.Sort falls back to heap sort when quicksort recursion gets
too deep.
C# heap sort example
The first example sorts an array of integers in ascending order.
int[] nums = [12, 11, 13, 5, 6, 7, 1, 20];
HeapSort(nums);
Console.WriteLine(string.Join(" ", nums));
static void HeapSort(int[] arr)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--)
{
SiftDown(arr, i, n);
}
for (int end = n - 1; end > 0; end--)
{
(arr[0], arr[end]) = (arr[end], arr[0]);
SiftDown(arr, 0, end);
}
}
static void SiftDown(int[] arr, int i, int n)
{
while (true)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest == i) return;
(arr[i], arr[largest]) = (arr[largest], arr[i]);
i = largest;
}
}
The method has two phases: building the heap and extracting the elements.
for (int i = n / 2 - 1; i >= 0; i--)
{
SiftDown(arr, i, n);
}
The elements from n / 2 onwards are leaves, which are valid heaps
by themselves. We sift down the remaining elements from the last parent to the
root. This builds the heap in O(n) time.
for (int end = n - 1; end > 0; end--)
{
(arr[0], arr[end]) = (arr[end], arr[0]);
SiftDown(arr, 0, end);
}
The root, which is the largest element of the heap, is swapped to the end of
the heap. The heap then has end elements, and the new root is
sifted down.
if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest == i) return; (arr[i], arr[largest]) = (arr[largest], arr[i]); i = largest;
The SiftDown method swaps the element with its larger child until
the element is larger than both children or becomes a leaf. A loop is used
instead of recursion.
$ dotnet run 1 5 6 7 11 12 13 20
Heap sort step by step
The next example prints the heap after it is built and after each extraction.
int[] nums = [4, 10, 3, 5, 1, 8];
int n = nums.Length;
for (int i = n / 2 - 1; i >= 0; i--)
{
SiftDown(nums, i, n);
}
Console.WriteLine($"max-heap: {string.Join(" ", nums)}");
for (int end = n - 1; end > 0; end--)
{
(nums[0], nums[end]) = (nums[end], nums[0]);
SiftDown(nums, 0, end);
Console.WriteLine($"take {nums[end],2}: heap [{string.Join(" ", nums[..end])}] sorted [{string.Join(" ", nums[end..])}]");
}
static void SiftDown(int[] arr, int i, int n)
{
while (true)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest == i) return;
(arr[i], arr[largest]) = (arr[largest], arr[i]);
i = largest;
}
}
In the max-heap, 10 is the root, with children 5 and 8. Element 5 has children 4 and 1, and element 8 has child 3. Each extraction moves the current maximum to the sorted part at the end.
$ dotnet run max-heap: 10 5 8 4 1 3 take 10: heap [8 5 3 4 1] sorted [10] take 8: heap [5 4 3 1] sorted [8 10] take 5: heap [4 1 3] sorted [5 8 10] take 4: heap [3 1] sorted [4 5 8 10] take 3: heap [1] sorted [3 4 5 8 10]
Generic heap sort
The generic version takes an IComparer<T>. The order is
defined by the comparer; with a reversed comparer, the heap is a min-heap and
the array is sorted in descending order.
string[] words = ["sky", "cup", "forest", "war", "book", "cloud", "ocean"];
HeapSort(words, StringComparer.Ordinal);
Console.WriteLine(string.Join(" ", words));
HeapSort(words, Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length)));
Console.WriteLine(string.Join(" ", words));
int[] nums = [3, 9, -4, 0, 7];
HeapSort(nums, Comparer<int>.Create((a, b) => b.CompareTo(a)));
Console.WriteLine(string.Join(" ", nums));
static void HeapSort<T>(T[] arr, IComparer<T> comparer)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--) SiftDown(i, n);
for (int end = n - 1; end > 0; end--)
{
(arr[0], arr[end]) = (arr[end], arr[0]);
SiftDown(0, end);
}
void SiftDown(int i, int size)
{
while (true)
{
int largest = i;
int left = 2 * i + 1;
int right = left + 1;
if (left < size && comparer.Compare(arr[left], arr[largest]) > 0) largest = left;
if (right < size && comparer.Compare(arr[right], arr[largest]) > 0) largest = right;
if (largest == i) return;
(arr[i], arr[largest]) = (arr[largest], arr[i]);
i = largest;
}
}
}
We sort words alphabetically, then by their length, and integers in descending order.
if (left < size && comparer.Compare(arr[left], arr[largest]) > 0) largest = left;
All comparisons go through the comparer.
The second line of the output shows that heap sort is not stable. Before the sort by length, the three-letter words were in alphabetical order: cup, sky, war. After the sort, war comes first.
$ dotnet run book cloud cup forest ocean sky war war cup sky book ocean cloud forest 9 7 3 0 -4
PriorityQueue
The PriorityQueue<TElement, TPriority> class is a min-heap.
Dequeue always removes the element with the lowest priority.
int[] nums = [42, 7, 19, 73, 3, 88, 25, 61, 14];
var pq = new PriorityQueue<int, int>();
foreach (int x in nums)
{
pq.Enqueue(x, x);
}
List<int> sorted = [];
while (pq.TryDequeue(out int x, out _))
{
sorted.Add(x);
}
Console.WriteLine(string.Join(" ", sorted));
var top = new PriorityQueue<int, int>();
foreach (int x in nums)
{
top.Enqueue(x, x);
if (top.Count > 3)
{
top.Dequeue();
}
}
Console.WriteLine($"3 largest: {string.Join(" ", top.UnorderedItems.Select(e => e.Element).Order())}");
We sort numbers with a priority queue and find the three largest numbers.
while (pq.TryDequeue(out int x, out _))
{
sorted.Add(x);
}
Dequeuing all elements returns them in ascending order of their priorities. This is heap sort with a separate heap, which needs O(n) extra memory.
top.Enqueue(x, x);
if (top.Count > 3)
{
top.Dequeue();
}
To find the k largest elements, we keep a heap of at most
k elements and remove the smallest one when it grows larger. This
takes O(n log k) time and does not sort the whole array.
Console.WriteLine($"3 largest: {string.Join(" ", top.UnorderedItems.Select(e => e.Element).Order())}");
The UnorderedItems property returns the elements in the heap's
internal order, so we sort the three numbers for printing.
$ dotnet run 3 7 14 19 25 42 61 73 88 3 largest: 61 73 88
Heap sort vs Array.Sort
In the last example, we sort a million random integers with heap sort and with
Array.Sort.
#:property PublishAot=false
using System.Diagnostics;
var rnd = new Random(17);
int[] data = [.. Enumerable.Range(0, 1_000_000).Select(_ => rnd.Next())];
int[] a = [.. data];
var sw = Stopwatch.StartNew();
HeapSort(a);
Console.WriteLine($"Heap sort, random data: {sw.ElapsedMilliseconds} ms");
sw.Restart();
HeapSort(a);
Console.WriteLine($"Heap sort, sorted data: {sw.ElapsedMilliseconds} ms");
int[] b = [.. data];
sw.Restart();
Array.Sort(b);
Console.WriteLine($"Array.Sort, random data: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Same result: {a.SequenceEqual(b)}");
static void HeapSort(int[] arr)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--) SiftDown(arr, i, n);
for (int end = n - 1; end > 0; end--)
{
(arr[0], arr[end]) = (arr[end], arr[0]);
SiftDown(arr, 0, end);
}
}
static void SiftDown(int[] arr, int i, int n)
{
while (true)
{
int largest = i;
int left = 2 * i + 1;
int right = left + 1;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest == i) return;
(arr[i], arr[largest]) = (arr[largest], arr[i]);
i = largest;
}
}
The second heap sort call runs on already sorted data.
#:property PublishAot=false
File-based apps are published with Native AOT by default. The directive turns this off, so the release build does not pull in the AOT compiler package.
We run the program in the Release configuration. Heap sort is about two times
slower than Array.Sort on random data. It is faster on the
sorted data in this run, but the input order has much less effect than for
insertion sort or bubble sort; the running time stays O(n log n).
$ dotnet run -c Release benchmark.cs Heap sort, random data: 123 ms Heap sort, sorted data: 63 ms Array.Sort, random data: 62 ms Same result: True
Source
PriorityQueue<TElement, TPriority> class
In this article we have implemented the heap sort algorithm in C#.
Other sorting algorithms in C#:
- Bubble sort
- Selection sort
- Insertion sort
- Shell sort
- Merge sort
- Quick sort
- Counting sort
- Radix sort
- Bucket sort
Author
List all C# tutorials.