-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapsort.cs
37 lines (35 loc) · 1.71 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
#region Heapsort
namespace HeapSort
{
public static class HeapSort
{
public static void Sort(int[] inputArray)
{
int sizeOfHeap = inputArray.Length;
int lastNonleaf = sizeOfHeap / 2 - 1; //you can find the last non leaf with total/2-1.
for (int i = lastNonleaf; i >= 0; i--)//heapifies all non leafs in sequence
{
Heapify(inputArray, sizeOfHeap, i);
}
for (int i = sizeOfHeap - 1; i > 0; i--)//move max value to end of heap stack and calls reduced heapify
{
(inputArray[0], inputArray[i]) = (inputArray[i], inputArray[0]); //swaps max value and index value
Heapify(inputArray, i, 0);
}
}
static void Heapify(int[] inputArray, int sizeOfHeap, int nodeIndex)
{
int largestValue = nodeIndex; //sets largest value to index to start
int leftIndex = (2 * nodeIndex + 1); //left child index is equal to 2n+1
int rightIndex = (2 * nodeIndex + 2); //right child index is equal to 2n+2
if (leftIndex < sizeOfHeap && inputArray[leftIndex] > inputArray[largestValue]) { largestValue = leftIndex; };
if (rightIndex < sizeOfHeap && inputArray[rightIndex] > inputArray[largestValue]) { largestValue = rightIndex; };
if (largestValue != nodeIndex)
{
(inputArray[nodeIndex], inputArray[largestValue]) = (inputArray[largestValue], inputArray[nodeIndex]); //swaps values
Heapify(inputArray, sizeOfHeap, largestValue); //if there was a swap, it runs again
}
}
}
}
#endregion Heapsort