-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapsort.cpp
71 lines (48 loc) · 1022 Bytes
/
heapsort.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
#include<bits/stdc++.h>
using namespace std ;
void heapify(int A[],int i,int N)
{
int left=2*i;
int right=2*i+1;
int smallest;
if(left<=N&&A[left]>=A[i])
smallest=left;
else
smallest=i;
if(right<=N&&A[right]>=A[smallest])
smallest=right;
if(smallest!=i)
{
int temp=A[i];
A[i]=A[smallest];
A[smallest]=temp;
//heapify(A,smallest,N);
}
}
void buildheap(int A[],int N)
{
for(int i=N/2;i>=1;i--)
{
heapify(A,i,N);
}
int temp=A[1];
A[1]=A[N];
A[N]=temp;
}
void heapsort(int A[],int N)
{
int n=N;
for(int i=0;i<n-1;i++)
{
buildheap(A,N);
N=N-1;
}
}
int main()
{
int A[8]={0,101,44,33,17,8,2,1};//index startinf from 1 so A[0]=0 is taken it has no value
heapsort(A,7);
for(int i=1;i<=7;i++)
std::cout<<A[i]<<" ";
return 0 ;
}