-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort_t.Java
More file actions
38 lines (35 loc) · 812 Bytes
/
HeapSort_t.Java
File metadata and controls
38 lines (35 loc) · 812 Bytes
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
import java.util.Arrays;
import java.util.Collections;
class HeapSort {
public static void main(String[] args) {
var n = 7;
var a = new Integer[7];
for (var i = 0; i < n; i++) {
a[i] = i;
}
Collections.shuffle(Arrays.asList(a));
for (var i : a) {
System.out.printf("%3d", i);
}
System.out.println();
for (var i = n - 1; i >= 0; i--) {
for (var j = (i + 1) / 2 - 1; j >= 0; j--) {
var c = j;
var l = j * 2 + 1;
if (a[c] < a[l]) c = l;
var r = j * 2 + 2;
if (r <= i && a[c] < a[r]) c = r;
var t = a[c];
a[c] = a[j];
a[j] = t;
}
var t = a[0];
a[0] = a[i];
a[i] = t;
}
for (var i : a) {
System.out.printf("%3d", i);
}
System.out.println();
}
}