Created
December 21, 2016 20:23
-
-
Save agustarc/f2779483dfdce3951ce6e6d5c24720ea to your computer and use it in GitHub Desktop.
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 HeapSort { | |
public static void heapSort(int[] arr) { | |
final int length = arr.length; | |
final Heap heap = new Heap(length); | |
for (int element : arr) { | |
heap.insertHeap(element); | |
} | |
for (int i = length - 1; i >= 0; --i) { | |
arr[i] = heap.deleteHeap(); | |
} | |
} | |
private static class Heap { | |
private int heapSize; | |
private final int[] items; | |
private Heap(int count) { | |
heapSize = 0; | |
items = new int[count + 1]; | |
} | |
private void insertHeap(int item) { | |
int i = ++heapSize; | |
while (i != 1 && item > items[i / 2]) { | |
items[i] = items[i / 2]; | |
i /= 2; | |
} | |
items[i] = item; | |
} | |
private int deleteHeap() { | |
int item = items[1]; | |
int temp = items[heapSize--]; | |
int parent = 1; | |
int child = 2; | |
while (child <= heapSize) { | |
if (child < heapSize && items[child] < items[child + 1]) { | |
child++; | |
} | |
if (temp >= items[child]) { | |
break; | |
} | |
items[parent] = items[child]; | |
parent = child; | |
child *= 2; | |
} | |
items[parent] = temp; | |
return item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment