-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
87 lines (70 loc) · 1.85 KB
/
Heap.java
File metadata and controls
87 lines (70 loc) · 1.85 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 Heap;
public class Heap {
private Integer[] heap;
private int currentPosition = -1;
public Heap(int size){
this.heap = new Integer[size];
}
public void insert(int item){
if( isFull() ){
throw new RuntimeException("Heap is full...");
}
this.heap[++currentPosition] = item;
fixUp(currentPosition);
}
private void fixUp(int index) {
int parentIndex = (index-1)/2;
while( parentIndex >= 0 && this.heap[parentIndex] < this.heap[index] ){
int temp = this.heap[index];
this.heap[index]=this.heap[parentIndex];
this.heap[parentIndex] = temp;
index = parentIndex;
parentIndex=(index-1)/2;
}
}
// get root method
public int getMax(){
int result = this.heap[0];
this.heap[0]=this.heap[currentPosition--];
this.heap[currentPosition+1]=null; // avoid obsolete references
fixDown(0,-1);
return result;
}
public void heapsort() {
for (int i=0; i <= currentPosition; i++) {
int temp = this.heap[0]; //
System.out.print(temp+" ");
this.heap[0] = this.heap[currentPosition-i];
this.heap[currentPosition-i] = temp;
fixDown(0, currentPosition-i-1);
}
}
private void fixDown(int index, int upto) {
if( upto < 0 ) upto = currentPosition;
while( index <= upto ){
int leftChild = 2*index+1;
int rightChild = 2*index+2;
if( leftChild <= upto ){
int childToSwap;
if( rightChild > upto ){
childToSwap = leftChild;
}else{
childToSwap = ( this.heap[leftChild] > this.heap[rightChild]) ? leftChild : rightChild;
}
if( this.heap[index] < this.heap[childToSwap]){
int temp = this.heap[index];
this.heap[index]=this.heap[childToSwap];
this.heap[childToSwap]=temp;
}else{
break;
}
index = childToSwap;
}else{
break;
}
}
}
private boolean isFull() {
return this.currentPosition == this.heap.length;
}
}