C# Implementation
suggest changepublic static class HeapSort
{
private static void Heapify(int[] values, int length, int root)
{
while (true)
{
int largest = root;
int left = 2 * root + 1;
int right = left + 1;
if (left < length && values[left] > values[largest]) largest = left;
if (right < length && values[right] > values[largest]) largest = right;
if (largest == root) return;
(values[root], values[largest]) = (values[largest], values[root]);
root = largest;
}
}
public static void Sort(int[] values)
{
for (int root = values.Length / 2 - 1; root >= 0; root--)
Heapify(values, values.Length, root);
for (int end = values.Length - 1; end > 0; end--)
{
(values[0], values[end]) = (values[end], values[0]);
Heapify(values, end, 0);
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents