-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHeap.java
More file actions
144 lines (120 loc) · 2.39 KB
/
Copy pathHeap.java
File metadata and controls
144 lines (120 loc) · 2.39 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
134
135
136
137
138
139
140
141
142
143
144
package org.fmz.container ;
public abstract class Heap{
protected Comparable[] data;
protected static final int DEFAULT_CAPACITY = 100;
protected int numItems;
public void finalize() throws Throwable {
super.finalize();
}
public Heap(){
data = new Comparable[DEFAULT_CAPACITY] ;
}
/**
*
* @param initCapacity
*/
public Heap(int initCapacity){
if(initCapacity <= 0)
data = new Comparable[DEFAULT_CAPACITY] ;
else
data = new Comparable[initCapacity] ;
}
public void clear(){
for(int i=0; i<numItems; i++)
data[i] = null ;
numItems = 0 ;
}
public void contract(){
if(numItems == data.length)
return ;
Comparable[] new_data = new Comparable[numItems] ;
for(int i=0; i<new_data.length; i++)
new_data[i] = data[i] ;
data = new_data ;
}
/**
*
* @param element
*/
public void insert(Comparable element){
if(isFull()){
Comparable[] new_data = new Comparable[numItems << 1] ;
for(int i=0; i<numItems; i++)
new_data[i] = data[i] ;
data = new_data ;
}
data[numItems++] = element ;
percolate() ;
}
public boolean isFull(){
return numItems == data.length ;
}
public boolean isEmpty(){
return numItems == 0 ;
}
/**
*
* @param pos
*/
protected boolean isLeaf(int pos){
return (pos << 1) + 1 >= numItems ;
}
/**
*
* @param pos
*/
protected int leftChild(int pos){
if(pos < 0)
return -1;
return (pos << 1) + 1 ;
}
/**
*
* @param pos
*/
protected int parent(int pos){
if(pos <= 0)
return -1 ;
return (pos - 1) >> 1 ;
}
protected Comparable peek(){
if(isEmpty())
return null ;
return data[0] ;
}
protected abstract void percolate();
protected Comparable remove(){
if(isEmpty())
return null ;
Comparable root = data[0] ;
swap(data, 0, numItems-1) ;
data[--numItems] = null ;
if(numItems > 0)
sift() ;
return root ;
}
/**
*
* @param pos
*/
protected int rightChild(int pos){
if(pos < 0)
return -1;
return (pos << 1) + 2 ;
}
protected abstract void sift();
public int size(){
return numItems ;
}
/**
*
* @param arr
* @param first
* @param second
*/
protected void swap(Comparable[] arr, int first, int second){
Comparable tmp = arr[first] ;
arr[first] = arr[second] ;
arr[second] = tmp ;
}
}