-
Notifications
You must be signed in to change notification settings - Fork 1
/
heapSort.cs
50 lines (43 loc) · 1.28 KB
/
heapSort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace heapSort
{
public class HeapSort
{
public void Sort(int[] array)
{
var heapSize = array.Length;
for (int p = (heapSize - 1) / 2; p >= 0; p--)
{
MaxHeapify(array, heapSize, p);
}
for (int i = array.Length - 1; i > 0; i--)
{
var temp = array[i];
array[i] = array[0];
array[0] = temp;
heapSize--;
MaxHeapify(array, heapSize, 0);
}
}
private void MaxHeapify(int[] array, int heapSize, int index)
{
var right = (index + 1) * 2;
var left = right - 1;
var largest = index;
if (left < heapSize && array[left] > array[largest])
{
largest = left;
}
if (right < heapSize && array[right] > array[largest])
{
largest = right;
}
if (largest != index)
{
var temp = array[index];
array[index] = array[largest];
array[largest] = temp;
MaxHeapify(array, heapSize, largest);
}
}
}
}