-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
59 lines (49 loc) · 1.27 KB
/
Copy pathHeapSort.java
File metadata and controls
59 lines (49 loc) · 1.27 KB
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
51
52
53
54
55
56
57
58
59
/*
* Heap Sort
*/
public class HeapSort {
public static void heapSort(int arr[]) {
// step1: build maxHeap
int n = arr.length;
for (int i = n / 2; i >= 0; i--) {
heapify(arr, i, n);
}
// step2: push largest at end
for (int i = n - 1; i > 0; i--) {
// swap (largest-first with last)
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, 0, i);
}
}
public static void heapify(int arr[], int i, int size) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int maxIdx = i;
if (left < size && arr[left] > arr[maxIdx]) {
maxIdx = left;
}
if (right < size && arr[right] > arr[maxIdx]) {
maxIdx = right;
}
if (maxIdx != i) {
// swap
int temp = arr[i];
arr[i] = arr[maxIdx];
arr[maxIdx] = temp;
heapify(arr, maxIdx, size);
}
}
public static void main(String[] args) {
int arr[] = { 8, 7, 65, 5, 4, 3, 2 };
heapSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
/*
* Output:
* 2 3 4 5 7 8 65
*/