Continue this process unless complete array is sorted.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyHeap | |
{ | |
private int[] arr; | |
private int size; | |
public MyHeap(int[] a) | |
{ | |
arr = a; | |
size = a.Length; | |
} | |
public void HeapSort() | |
{ | |
int length = size; | |
for (int i = length; i > 0; i--) | |
{ | |
Heapify(i); | |
swap(0, i - 1); | |
} | |
} | |
private void Heapify(int length) | |
{ | |
for (int i = length / 2; i >= 0; i--) | |
{ | |
MaxHeapify(i, length); | |
} | |
} | |
private void MaxHeapify(int startIndex, int count) | |
{ | |
int largest = startIndex; | |
int l = 2*startIndex + 1; | |
int r = 2*startIndex + 2; | |
if (l < count && arr[l] > arr[largest]) | |
{ | |
largest = l; | |
} | |
if (r < count && arr[r] > arr[largest]) | |
{ | |
largest = r; | |
} | |
if (largest != startIndex) | |
{ | |
swap(largest, startIndex); | |
} | |
} | |
private void swap(int a, int b) | |
{ | |
int temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} | |
} |