- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
Latest commit
52 lines (44 loc) · 1.23 KB
/
Copy pathHeapSort.java
File metadata and controls
52 lines (44 loc) · 1.23 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
publicclassHeapSort {
privatestaticintsize = 0;
publicstaticvoidmain(String[] args) {
intarr[] = {1,3,10,4,2,6,7,5,9,8};
size = arr.length -1;
heapSort(arr);
for (intvar : arr) {
System.out.print(var + ",");
}
System.out.println();
}
staticvoidbuildMaxHeap(int[] arr, intpos) {
for (inti = pos / 2; i >= 0; i--) {
adjust(arr, i);
}
}
staticvoidadjust(int[] arr, intpos) {
intleft = 2 * pos + 1;
intright = 2 * (pos + 1);
intlarge = pos;
if ((left <= size ) && (arr[left] > arr[pos])) {
large = left;
}
if ((right <= size ) && (arr[right] > arr[large])) {
large = right;
}
if (pos != large) {
inttmp = arr[large];
arr[large] = arr[pos];
arr[pos] = tmp;
adjust(arr, large);
}
}
staticvoidheapSort(int[] arr) {
buildMaxHeap(arr, arr.length - 1);
for (inti = arr.length - 1; i >= 0 ; i--) {
inttmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
size--;
adjust(arr, 0);
}
}
}