-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.java
More file actions
133 lines (114 loc) · 2.91 KB
/
Copy pathMinHeap.java
File metadata and controls
133 lines (114 loc) · 2.91 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
public class MinHeap implements Heap{
private int[] Heap;
private int size;
private int n;
public MinHeap(int[] heap,int num,int max){
Heap = heap;
n = num;
size = max;
buildheap();
}
public MinHeap(int max){
this.size = max;
n = 0;
Heap = new int[max];
}
@Override
public int heapsize() {
return size;
}
@Override
public boolean isLeaf(int pos) {
return (pos>=n/2)&&(pos<n);
}
@Override
public int left(int pos) {
if(pos<n/2){
return 2 * pos +1;
}
return -1;
}
@Override
public int right(int pos) {
if(pos<(n-1)/2){
return 2 * pos + 2;
}
return -1;
}
@Override
public int parent(int pos) {
if(pos>0){
return (pos-1)/2;
}
return -1;
}
@Override
public void insert(int val) {
if(n< size){
int curr = n++;
Heap[curr] = val;
while(curr != 0 && Heap[curr]<Heap[parent(curr)]){
swap(Heap,curr,parent(curr));
curr = parent(curr);
}
}
else{
System.out.println("The Heap is Full");
}
}
@Override
public int delete() {
if(n<=0){
System.out.println("The heap is Empty");
return -1;
}
else{
swap(Heap,0,--n);
if(n!=0){
siftdown(0);
}
return Heap[n];
}
}
@Override
public void siftdown(int pos) {
if(pos>=0 && pos<n){
while(!isLeaf(pos)){
int j = left(pos); //获得pos的左儿子位置
if(j<n-1 && Heap[j]>Heap[j+1]){
j++; //现在Heap[j]是左右儿子更小的那个
}
if(Heap[pos]<=Heap[j])return;
swap(Heap,pos,j);
pos = j;
}
}
}
public static void swap(int[] Heap,int i,int j){
int temp = Heap[i];
Heap[i] = Heap[j];
Heap[j] = temp;
}
public void buildheap(){
for(int i = n/2-1;i>=0;i--){
siftdown(i);
}
}
public int getMin(){
return Heap[0];
}
public static void HeapSort(int[] nums,int start,int end){
MinHeap heap = new MinHeap(nums,nums.length,nums.length);
heap.buildheap();
for(int i = 0;i<nums.length;i++){
if(i>=start && i<=end){
System.out.printf("%d ",heap.getMin());
}
heap.delete();
}
}
public static void main(String[] args){
int[] nums = {10,99,100,11,17,19,33,81,12,5,52,63,1};
HeapSort(nums,0,12);
}
}