forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
152 lines (139 loc) · 2.68 KB
/
Copy pathHeapSort.java
File metadata and controls
152 lines (139 loc) · 2.68 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
147
148
149
150
151
152
class heap
{
int arr[]=new int[10];
int size=0;
int getParentIndex(int i)
{
return (i-1)/2;
}
int getLeftChildIndex(int i)
{
return (2*i+1);
}
int getRightChildIndex(int i)
{
return (2*i+2);
}
boolean hasParent(int i)
{
// if(getParentIndex(i)<0) return false;
// return true;
return getParentIndex(i)>=0; //another method for code beautify
}
boolean hasLeftChild(int i)
{
return getLeftChildIndex(i)<size;
}
boolean hasRightChild(int i)
{
return getRightChildIndex(i)<size;
}
int parent(int i)
{
// return arr[(i-1)/2];
return arr[getParentIndex(i)];
}
int LeftChild(int i)
{
return arr[getLeftChildIndex(i)];
}
int RightChild(int i)
{
return arr[getRightChildIndex(i)];
}
int size()
{
return size;
}
boolean isEmpty()
{
return size<=0; //or size==0;
}
int peek()
{
return arr[0]; //root return highest priority
}
void insert(int val)
{
arr[size]=val;
size++;
HeapifyUp();
}
void HeapifyUp()
{
int i=size-1;
while(hasParent(i) && parent(i)<arr[i])
{
swap(i,getParentIndex(i));
i=getParentIndex(i);
}
}
void swap(int a,int b)
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
void print()
{
for(int i=0;i<5;i++)
{
System.out.print(arr[i]+" ");
}
}
int poll()
{
int val=arr[0];
arr[0]=arr[size-1];
size--;
HeapifyDown();
return val;
}
void HeapifyDown()
{
int i=0;
while(hasLeftChild(i))
{
int greaterChildIndex=getLeftChildIndex(i);
if(hasRightChild(i) && RightChild(i)>LeftChild(i))
{
greaterChildIndex=getRightChildIndex(i);
}
if(arr[i]<arr[greaterChildIndex])
{
swap(i,greaterChildIndex);
}
else
{
break;
}
i=greaterChildIndex;
}
}
void sort()
{
while(size!=1)
{
int temp=arr[0];
arr[0]=arr[size-1];
arr[size-1]=temp;
size--;
HeapifyDown();
}
}
}
class HeapSort
{
public static void main(String[] args) {
heap h=new heap();
h.insert(10);
h.insert(5);
h.insert(3);
h.insert(2);
h.insert(7);
h.print();
h.sort();
System.out.println();
h.print();
}
}