-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTHeap.java
More file actions
146 lines (129 loc) · 3.4 KB
/
Copy pathTHeap.java
File metadata and controls
146 lines (129 loc) · 3.4 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
145
146
public class THeap implements Heap{
private int[] Heap;
private int size;
private int n;
public THeap(int[] heap,int max,int n){
this.Heap = heap;
this.size = max;
this.n = n;
buildheap();
}
public THeap(int max){
this.size = max;
n = 0;
Heap = new int[max];
}
@Override
public int left(int pos) {
if(pos<=(n-2)/3) {
return 3 * pos + 1;
}
return -1;
}
@Override
public int right(int pos) {
if(pos<=(n-4)/3) {
return 3 * pos + 3;
}
return -1;
}
@Override
public int parent(int pos) {
if(pos>0) {
return (pos - 1) / 3;
}
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 heapsize() {
return size;
}
@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 boolean isLeaf(int pos) {
return pos<n && pos>=(n-1)/3;
}
@Override
public void siftdown(int pos) {
if(pos>= 0 && pos<n){
while(!isLeaf(pos)){
int curr = pos;
if(Heap[curr]<=Math.min(Math.min(Heap[left(curr)],Heap[mid(curr)]),Heap[right(curr)]))return;
if(left(curr)<n && Heap[curr]>Heap[left(pos)]){
curr = left(pos);
}
if(mid(curr)< n && Heap[curr]>Heap[mid(pos)]){
curr = mid(pos);
}
if(right(curr) < n && Heap[curr]>Heap[right(pos)]){
curr = right(pos);
}
swap(Heap,curr,pos);
pos = curr;
}
if(n==2 && Heap[0]>= Heap[1]){
swap(Heap,0,1);
}
}
}
public int mid(int pos){
if(pos<=(n-3)/3) {
return 3 * pos + 2;
}
return -1;
}
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-1)/3-1;i>=0;i--){
siftdown(i);
}
}
public int getMin(){
return Heap[0];
}
public static void THeapSort(int[] nums,int start,int end){
THeap heap = new THeap(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,10,10};
THeapSort(nums,0,14);
}
}