-
Notifications
You must be signed in to change notification settings - Fork 127
/
heap-sort.java
70 lines (56 loc) · 1.46 KB
/
heap-sort.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
62
63
64
65
66
67
68
69
70
public class HeapSort {
public HeapSort() {
}
private void heap(int[] array, int length, int i) {
int left = 2*i+1;
int right = 2*i+2;
int large = i;
if (left < length && array[left] > array[large]) {
large = left;
}
if (right < length && array[right] > array[large]) {
large = right;
}
if (large != i) {
int temp = array[i];
array[i] = array[large];
array[large] = temp;
heap(array, length, large);
}
}
private void sort(int[] array) {
if (array.length == 0) return;
int length = array.length;
for (int i = length / 2-1; i >= 0; i--)
heap(array, length, i);
for (int i = length-1; i >= 0; i--) {
int temp = array[0];
array[0] = array[i];
array[i] = temp;
heap(array, i, 0);
}
}
private int[] createIntArray(int size){
int[] data = new int[size];
for(int i=0; i<data.length; i++){
data[i] = (int)(Math.random()*1000);
}
return data;
}
private void print(int[] data){
for(int i=0; i<data.length; i++){
System.out.print(data[i] + " ");
if(i!=0 && i%40==0) System.out.println();
}
System.out.println("\n");
}
public static void main(String[] args) {
HeapSort hs = new HeapSort();
int[] array = hs.createIntArray(10);
System.out.print("Array before sorting: ");
hs.print(array);
hs.sort(array);
System.out.print("Array after sorting: ");
hs.print(array);
}
}