- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeapSort.java
More file actions
Latest commit
56 lines (46 loc) · 1.41 KB
/
Copy pathHeapSort.java
File metadata and controls
56 lines (46 loc) · 1.41 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
packageSorting;
publicclassHeapSort {
publicstaticint[] heapSort(intarr[]) {
intsz = arr.length;
// Heap construction
intlastIdx = sz-1;
for (inti = (lastIdx-1)/2 ; i >= 0; i--)
heapify(arr, i, sz);
intsortedArr[] = newint[arr.length];
for (inti = 0; i < arr.length; i++) {
sortedArr[i] = arr[0];
swap(0, sz-1, arr);
sz--;
heapify(arr, 0, sz);
}
returnsortedArr;
}
publicstaticvoidheapify(intarr[], intat, intsz) {
intnextChildIdx = (at * 2) + 1;
if (nextChildIdx >= sz)
return;
intrightChildIdx = (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;
}
publicstaticvoidswap(inta, intb, intarr[]) {
inttemp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
publicstaticintmin (inta, intb) {
returna < b ? a : b;
}
publicstaticvoidmain(String[] args) {
intarr[] = {1, 5, 0, 15, 7, 3, 23, 11};
intsortedArr[] = heapSort(arr);
for (intelem : sortedArr)
System.out.print(elem + " ");
}
}