Skip to content

Commit e90bf2f

Browse files
Update and rename heap.cpp to HeapSort.cpp
1 parent c344de6 commit e90bf2f

File tree

2 files changed

+97
-97
lines changed

2 files changed

+97
-97
lines changed

Sorting/HeapSort.cpp

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#include<iostream>
2+
3+
4+
using namespace std;
5+
6+
void swap(int *x,int *y)
7+
{
8+
int temp = *x;
9+
*x = *y;
10+
*y = temp;
11+
}
12+
13+
class heap
14+
{
15+
int heap_size;
16+
int *harr;
17+
int capacity;
18+
public:
19+
heap(int cap)
20+
{
21+
capacity = cap;
22+
heap_size = 0;
23+
harr = new int[cap];
24+
}
25+
int parent(int i){return (i-1)/2;}
26+
int left(int i){ return (2*i)+1;}
27+
int right(int i){ return (2*i)+2;}
28+
void insert(int num)
29+
{
30+
if(heap_size == capacity)
31+
{
32+
cout<<"Overflow"<<endl;
33+
return;
34+
}
35+
heap_size++;
36+
harr[heap_size-1] = num;
37+
int i = heap_size - 1;
38+
while(i >=0 && harr[parent(i)] > harr[i])
39+
{
40+
swap(&harr[parent(i)],&harr[i]);
41+
i = parent(i);
42+
}
43+
}
44+
void display()
45+
{
46+
int i;
47+
for(i=0;i<heap_size;i++)
48+
cout<<harr[i]<<" ";
49+
}
50+
51+
void minheapify(int i,int limit)
52+
{
53+
int l = left(i);
54+
int r = right(i);
55+
if(l>=limit || r>=limit)
56+
return;
57+
int smallest =i;
58+
if(harr[l] < harr[i])
59+
smallest= l;
60+
if(harr[r] < harr[smallest])
61+
smallest = r;
62+
if(i != smallest)
63+
{
64+
swap(&harr[i],&harr[smallest]);
65+
minheapify(smallest,limit);
66+
}
67+
}
68+
69+
void sort()
70+
{
71+
int i;
72+
for(i=1;i<heap_size-1;i++)
73+
{
74+
swap(&harr[0],&harr[heap_size-i]);
75+
minheapify(0,heap_size -i);
76+
}
77+
}
78+
};
79+
80+
81+
int main()
82+
{
83+
heap h(10);
84+
h.insert(10);
85+
h.insert(20);
86+
h.insert(30);
87+
h.insert(12);
88+
h.insert(8);
89+
h.insert(9);
90+
h.insert(11);
91+
h.insert(13);
92+
h.insert(14);
93+
h.sort();
94+
h.display();
95+
cout<<endl;
96+
return 0;
97+
}

Sorting/heap.cpp

Lines changed: 0 additions & 97 deletions
This file was deleted.

0 commit comments

Comments
 (0)