-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSort.java
56 lines (46 loc) · 1.41 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
package Sorting;
public class HeapSort {
public static int[] heapSort(int arr[]) {
int sz = arr.length;
// Heap construction
int lastIdx = sz-1;
for (int i = (lastIdx-1)/2 ; i >= 0; i--)
heapify(arr, i, sz);
int sortedArr[] = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
sortedArr[i] = arr[0];
swap(0, sz-1, arr);
sz--;
heapify(arr, 0, sz);
}
return sortedArr;
}
public static void heapify(int arr[], int at, int sz) {
int nextChildIdx = (at * 2) + 1;
if (nextChildIdx >= sz)
return;
int rightChildIdx = (at * 2) + 2;
if (rightChildIdx < sz && arr[nextChildIdx] > arr[rightChildIdx]) {
nextChildIdx = rightChildIdx;
}
if (arr[at] > arr[nextChildIdx]) {
swap(at, nextChildIdx, arr);
heapify(arr, nextChildIdx, sz);
} else
return;
}
public static void swap(int a, int b, int arr[]) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static int min (int a, int b) {
return a < b ? a : b;
}
public static void main(String[] args) {
int arr[] = {1, 5, 0, 15, 7, 3, 23, 11};
int sortedArr[] = heapSort(arr);
for (int elem : sortedArr)
System.out.print(elem + " ");
}
}