forked from zfman/AlgorithmCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
68 lines (58 loc) · 1.13 KB
/
Copy pathHeap.java
File metadata and controls
68 lines (58 loc) · 1.13 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
package sort;
/**
* @author 刘壮飞
* https://github.com/zfman.
* https://blog.csdn.net/lzhuangfei.
*/
public class Heap<T extends Comparable<T>> {
private T[] heap;
private int n=0;
public Heap(int maxNum){
n=maxNum;
}
public boolean isEmpty(){
return n==0;
}
protected boolean less(int i,int j){
return heap[i].compareTo(heap[j])<0;
}
protected void swap(int i,int j){
T t=heap[i];
heap[i]=heap[j];
heap[j]=t;
}
/**
* 上浮
* @param k
*/
protected void swim(int k){
while (k>1&&less(k/2,k)){
swap(k/2,k);
k=k/2;
}
}
/**
* 下沉
* @param k
*/
protected void sink(int k){
while (2*k<=n){
int j=2*k;
if(j<n&&less(j,j+1)) j++;
if(!less(k,j)) break;;
swap(k,j);
k=j;
}
}
protected void insert(T v){
heap[++n]=v;
swim(n);
}
public T deleteMax(){
T max=heap[1];
swap(1,n--);
heap[n+1]=null;
sink(1);
return max;
}
}