-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path12_heapsort.cpp
More file actions
59 lines (59 loc) · 761 Bytes
/
12_heapsort.cpp
File metadata and controls
59 lines (59 loc) · 761 Bytes
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
#include<iostream>
using namespace std;
int n=4;
void heapify(int arr[],int i,int n)
{
int l=(2*i)+1;
int r=(2*i)+2;
int large;
if(l<n && arr[l]>arr[i])
large=l;
else
large=i;
if(r<n && arr[r]>arr[large])
large=r;
if(large!=i)
{
swap(arr[i],arr[large]);
heapify(arr,large,n);
}
}
void build_heap(int arr[])
{
for(int i=(n-1)/2;i>=0;i--)
{
heapify(arr,i,n);
}
}
void heapsort(int arr[])
{
int heapsize=n;
build_heap(arr);
for(int i=n-1;i>=0;i--)
{
swap(arr[0],arr[i]);
heapsize=heapsize-1;
heapify(arr,0,heapsize);
}
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
heapsort(arr);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}