-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHeapmin.java
128 lines (115 loc) · 3.3 KB
/
Heapmin.java
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
import java.util.*;
class Minheap{
private int arr[];
private int size;
private int max;
public Minheap(int max){
arr=new int[max];
this.max=max;
size=0;
}
private int parent(int i){
return i/2;
}
private int left(int i){
return 2*i;
}
private int right(int i){
return (2*i)+1;
}
public boolean insert(int val){
if(size==max-1)
return false;
size++;
arr[size]=val;
int i=size;
while(arr[parent(i)]>arr[i]&& i!=1){
int temp=arr[i];
arr[i]=arr[parent(i)];
arr[parent(i)]=temp;
i=parent(i);
}
return true;
}
public void display(){
for(int i=1;i<=size;i++){
System.out.println(arr[i]);
}
}
private void Minheapify(int i){
if(size!=0){
int c1,c2;
c1=left(1);
c2=right(i);
if(c1<size&&c2<size){
if(arr[i]>arr[c1]||arr[i]>arr[c2]){
if(arr[c1]<arr[c2]){
int temp=arr[i];
arr[i]=arr[c1];
arr[c1]=arr[i];
Minheapify(c1);
}
else{
int temp=arr[i];
arr[i]=arr[c2];
arr[c2]=arr[i];
Minheapify(c2);
}
}
}
}
}
public int extractMin(){
if(size==0)
return -1;
int val=arr[1];
arr[1]=arr[size];
size--;
Minheapify(1);
return val;
}
}
public class Heapmin{
public static void main(String[]args){
int max;
Scanner s= new Scanner(System.in);
System.out.println("enetr max :");
max=s.nextInt();
Minheap h= new Minheap(max);
boolean temp=true;
int choice;
while(temp){
System.out.println("1 to insert");
System.out.println("2 to pop");
System.out.println("3 to display");
System.out.println("4 to exit");
choice=s.nextInt();
switch(choice){
case 1:
choice=s.nextInt();
if(h.insert(choice)){
h.display();
}
else{
System.out.println("Cannot do this!");
}
break;
case 2:
choice=h.extractMin();
if(choice==-1)
System.out.println("Cannot do this!");
else
System.out.println(choice);
break;
case 3:
h.display();
break;
case 4:
temp=false;
break;
default:
System.out.println("Enter the correct choice!");
}
}
}
}