-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathHeap_Sort.cpp
149 lines (129 loc) · 3.01 KB
/
Heap_Sort.cpp
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
#include <iostream>
using namespace std;
class heapp
{
public:
int heap[20];
int heap_size;
heapp()
{
heap_size = 0;
}
void insert_heap(int val);
void up_heapify();
void delete_heap();
void down_heapify();
};
void heapp::insert_heap(int val)
{
heap_size++;
heap[heap_size] = val;
up_heapify();
}
void heapp::up_heapify()
{
int cur_loc,parent_loc;
cur_loc = heap_size;
while(1)
{
parent_loc = cur_loc / 2;
if(heap[parent_loc] < heap[cur_loc])
{
int temp = heap[parent_loc];
heap[parent_loc] = heap[cur_loc];
heap[cur_loc] = temp;
cur_loc = parent_loc;
}
else
break;
}
}
void heapp::delete_heap()
{
//swap the value at heap[1] with value at heap[heap_size]
int temp = heap[1];
heap[1] = heap[heap_size];
heap[heap_size] = temp;
heap_size--;
down_heapify();
}
void heapp::down_heapify()
{
int cur_loc = 1;
int loc_left, loc_right;
while(1)
{
loc_left = cur_loc *2;
loc_right = (cur_loc * 2) + 1;
//valid left and right children
if(loc_left <= heap_size && loc_right <= heap_size)
{
if(heap[loc_left] > heap[loc_right]) // left child is > than right child
{
// check whether we have to swap
if(heap[cur_loc] < heap[loc_left])
{
int temp = heap[cur_loc];
heap[cur_loc] = heap[loc_left];
heap[loc_left] = temp;
cur_loc = loc_left;
}
else
break;
}
else // right child is > left child
{
if(heap[cur_loc] < heap[loc_right])
{
int temp = heap[cur_loc];
heap[cur_loc] = heap[loc_right];
heap[loc_right] = temp;
cur_loc = loc_right;
}
else
break;
}
}
// if it has only valid left child
else if(loc_left <= heap_size)
{
//check whether we have to swap
if(heap[cur_loc] < heap[loc_left])
{
int temp = heap[cur_loc];
heap[cur_loc] = heap[loc_left];
heap[loc_left] = temp;
cur_loc = loc_left;
}
else
break;
}
//it do not have valid left child as well as valid right child
else
{
break;
}
}
}
int main()
{
int n, no;
heapp h;
cout<<"\n Enter how many numbers you want to sort: ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"\n Enter the number : ";
cin>>no;
h.insert_heap(no);
}
while(h.heap_size != 1)
{
h.delete_heap();
}
for(int i=1;i<=n;i++)
{
cout<<"\n "<<h.heap[i];
}
return 0;
}