-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.java
61 lines (48 loc) · 1.32 KB
/
HeapSort.java
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
60
61
package Heaps;
public class HeapSort {
public static void print(int[] arr){
for (int i=0; i<arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void heapSort(int[] arr){
int n = arr.length;
// 1.convert to maxHeap
for (int i=n/2; i>=0; i--){
heapify(arr, i, n);
}
// 2. push large element at end
for (int i=n-1; i>0; i--){
//swap first and 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 lb = 2*i+1;
int rb = 2*i+2;
int max = i;
if (lb < size && arr[lb] > arr[max]){
max = lb;
}
if (rb < size && arr[rb] > arr[max]){
max = rb;
}
if (i != max){
//swap max and i
int temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
heapify(arr, max, size);
}
}
public static void main(String[] args) {
int[] arr = {2, 1, 4, 9, 3, 6};
print(arr);
heapSort(arr);
print(arr);
}
}