-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
49 lines (42 loc) · 797 Bytes
/
HeapSort.cpp
File metadata and controls
49 lines (42 loc) · 797 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
#include <bits/stdc++.h>
using namespace std;
int a[]={0, 36, 21, 16, 31, 58, 41, 26, 59, 53, 97};
void heapify(int a[], int n, int i)
{
if(i<=n && 2*i<=n)
{
int largest = i, left = 2*i, right = 2*i +1 ;
int index=((left<=n?a[left]:0)>(right<=n?a[right]:0))?left:right; //left and right mese maximum
if(a[largest]>a[index]) return;
if(largest != index && a[largest]<a[index]);
{
swap(a[index],a[largest]);
heapify(a,n,index);
}
}
// printf("%d\n", largest);
}
void heapsort(int a[], int n)
{
for(int i=n/2; i>0; i--)
{
// printf("i= %d\n", i);
heapify(a,n,i);
}
for(int i=n;i>0;i--)
{
if(a[1]<a[i])
break;
swap(a[1],a[i]);
heapify(a,i-1,1);
}
}
int main()
{
heapsort(a, 10);
for(int i=1; i<=10;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}