-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMyHeap.java
More file actions
120 lines (93 loc) · 2.54 KB
/
Copy pathMyHeap.java
File metadata and controls
120 lines (93 loc) · 2.54 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
/**
* Created by dheeraj on 11/1/15.
*/
public class MyHeap {
private int heapSize;
private int[] array;
public MyHeap(int[] arr){
array = arr;
heapSize = arr.length;
}
private void print(){
for(int x =0;x<array.length;x++){
System.out.print(array[x]+" ");
}
System.out.println();
}
private void maxHeapify(int index){
int max = index;
if(getLeftChild(index) < heapSize && array[max] < array[getLeftChild(index)]){
max = getLeftChild(index);
}
if(getRightChild(index) < heapSize && array[max] < array[getRightChild(index)]){
max= getRightChild(index);
}
if(max != index){
swap(max,index);
maxHeapify(max);
}
}
private void buildMaxHeap(){
int start = heapSize/2 -1;
for(int x = start;x>=0;x--){
maxHeapify(x);
}
}
private void heapSort(){
buildMaxHeap();
for(int x = heapSize-1;x>0;x--){
swap(0,heapSize-1);
heapSize = heapSize -1;
maxHeapify(0);
}
heapSize = array.length;
}
private void swap(int z,int y){
int x = array[z];
array[z] = array[y];
array[y] = x;
}
private int getParent(int child){
return (child-1)/2;
}
private int getLeftChild(int parent){
return parent*2+1;
}
private int getRightChild(int parent){
return parent*2+2;
}
private void increaseKeyValue(int index,int value){
if(index >= heapSize || value < array[index]){
System.out.println("error");
return;
}
array[index] = value;
while(index >= 0 && array[index] > array[getParent(index)]){
swap(index,getParent(index));
index = getParent(index);
}
}
private void increaseHeapSize(){
heapSize = heapSize +1;
int[] newArr = new int[heapSize];
for(int x =0;x<heapSize;x++){
try {
newArr[x] = array[x];
}catch (Exception e){
newArr[x] =0;
}
}
array = newArr;
}
public static void main(String[] args){
int[] arr = {1,4,3,6,5,8,7,9,2};
MyHeap myHeap =new MyHeap(arr);
//myHeap.heapSort();
myHeap.print();
myHeap.increaseKeyValue(8,10);
myHeap.print();
myHeap.increaseHeapSize();
myHeap.increaseKeyValue(9,100);
myHeap.print();
}
}