-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
130 lines (100 loc) · 2.44 KB
/
HeapSort.java
File metadata and controls
130 lines (100 loc) · 2.44 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
package geeks.algo.sort;
public class HeapSort extends Sort {
class BinaryHeap{
int[] heap;
int heapSize;
BinaryHeap(int capacity){
heap = new int[capacity];
heapSize=0;
}
private int getParentIndex(int childIndex){
return (childIndex-1)/2;
}
private void heapifyUp(int childIndex){
int val = heap[childIndex];
int parentIndex =getParentIndex(childIndex);
while(childIndex>0 &&
val< heap[parentIndex = getParentIndex(childIndex)]){
heap[childIndex]=heap[parentIndex];
childIndex=parentIndex;
}
heap[childIndex]=val;
}
public void insertIntoHeap(int ele){
if(isFull()){
throw new RuntimeException("OVerflow");
}
heap[heapSize++]=ele;
heapifyUp(heapSize-1);
}
private boolean isFull() {
if(heapSize>heap.length){
return true;
}
return false;
}
private void heapifyDown(int childIndex){
while(heapSize> (childIndex*2+1)){
if(heapSize> (childIndex*2+2)){
if(heap[childIndex]<heap[childIndex*2+1]
&& heap[childIndex]<heap[childIndex*2+2]){
break;
}else{
if(heap[childIndex*2+1]<heap[childIndex*2+2]){
int tmp = heap[childIndex];
heap[childIndex]=heap[childIndex*2+1];
heap[childIndex*2+1] =tmp;
childIndex = childIndex*2+1;
}else{
int tmp = heap[childIndex];
heap[childIndex]=heap[childIndex*2+2];
heap[childIndex*2+2] =tmp;
childIndex = childIndex*2+2;
}
}
}else{
int tmp = heap[childIndex];
heap[childIndex]=heap[childIndex*2+1];
heap[childIndex*2+1] =tmp;
childIndex = childIndex*2+1;
}
}
}
int deleteItem(int index){
if(heapSize==0){
throw new RuntimeException("Underflow");
}
int item=heap[index];
heap[index]=heap[heapSize-1];
heapSize--;
heapifyDown(index);
return item;
}
public void show(){
System.out.println();
for(int i=0;i<heapSize;i++)
System.out.print(heap[i]+" ");
System.out.println();
}
}
HeapSort(int[] arr) {
super(arr);
}
@Override
protected void performSort() {
BinaryHeap heap = new BinaryHeap(arr.length+2);
for(int i=0;i<arr.length;i++){
heap.insertIntoHeap(arr[i]);
}
int i=0;
while(heap.heapSize>0){
this.arr[i++] =heap.deleteItem(0);
}
}
@Override
protected void setComplexities() {
this.timeComplexity="O(n * Log(n))";
this.spaceComplexity="N/A";
this.type="Heap Sort";
}
}