Repository navigation
Expand file tree
/
Copy pathHeapSort2.java
More file actions
87 lines (69 loc) · 2.08 KB
/
Copy pathHeapSort2.java
File metadata and controls
87 lines (69 loc) · 2.08 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package study;
/**
* this version make the heap index and array index consistent, namely both begin from 0
* */
public class HeapSort2 {
int[] Arr;
HeapSort2(int[] A){
this.Arr=A.clone();
}
//heap index start from 0, so if the parentIndex is i, the leftIndex is 2*i+1, and rightIndex is 2*i+2,
private static int left(int i){
return 2*i + 1;
}
private static int right(int i){
return 2*i + 2;
}
public static void maxHeapify(int[] data, int i, int heapSize){
int l = left(i);
int r = right(i);
int largest;
if(l < heapSize && data[l] > data[i]){
largest = l;
}else{
largest = i;
}
if(r < heapSize && data[r] > data[largest]){
largest = r;
}
if(largest != i){
swap(data,i,largest);
maxHeapify(data, largest, heapSize);
}
}
public static void buildMaxHeap(int[] data){
int heapSize = data.length;
for(int i = heapSize/2-1; i >=0; i--){
maxHeapify(data, i, heapSize);
}
}
public static void heapSort(int[] data){
int heapSize = data.length;
buildMaxHeap(data);
System.out.println("Max heap built is:");
outputArray(data);//check if the heap is correct
for(int i = heapSize - 1; i >0; i--){
swap(data,0,i);//
heapSize = heapSize - 1;
maxHeapify(data, 0, heapSize);//
}
}
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
public static void outputArray(int A[]) {
for (int i = 0; i < A.length; i++) {
System.out.print(A[i] + ", ");
}
System.out.println(" ");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] Array = { 7,3,9,6,2,9,11,5};
HeapSort2 HS=new HeapSort2(Array);
HS.heapSort(HS.Arr);
HS.outputArray(HS.Arr);
}
}