public static void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static void heapify(int[] arr, int parent, int size) {
int temp_parent = parent;
int left_child = parent * 2 + 1;
int right_child = parent * 2 + 2;
if (left_child < size && arr[temp_parent] > arr[left_child])
temp_parent = left_child;
if (right_child < size && arr[temp_parent] > arr[right_child])
temp_parent = right_child;
if (parent != temp_parent) {
swap(arr, parent, temp_parent);
heapify(arr, temp_parent, size);
}
}
public static void main(String[] args) {
int[] arr = new int[]{7, 3, 22, 6, 2, 14, 1};
int len = arr.length;
// heapify를 통해 초기 배열을 min heap으로 만듦
for (int i = len / 2 - 1; i >= 0; --i)
heapify(arr, i, len);
// 루트노드를 뒤로 넘기고(삭제) 나머지 원소들을 heap으로 만듦
for (int i = len - 1; i > 0; --i) {
swap(arr, 0, i);
heapify(arr, 0, i);
}
}
heapify 알고리즘:
평균 | 최선 | 최악 |
---|---|---|
https://github.com/gyoogle/tech-interview-for-developer/blob/master/Algorithm/HeapSort.md
https://soobarkbar.tistory.com/212
https://st-lab.tistory.com/225