-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapsort.c
66 lines (59 loc) · 926 Bytes
/
heapsort.c
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
/*********************
Heap Sort
*********************/
#include <stdio.h>
void max_heapify(int a[],int n,int i)
{
int temp,l=i;
if(2*i+1 < n && a[2*i+1] > a[i])
l=2*i+1;
if(2*i+2 < n && a[2*i+2] > a[l])
l=2*i+2;
if(l!=i)
{
temp=a[i];
a[i]=a[l];
a[l]=temp;
max_heapify(a,n,l);
}
}
void build_max_heap(int a[],int n)
{
int i;
for(i=n/2-1;i>=0;i--)
{
max_heapify(a,n,i);
}
}
void heap_sort(int a[],int n)
{
int i,temp;
build_max_heap(a,n);
for(i=n-1;i>=1;i--)
{
temp=a[i];
a[i]=a[0];
a[0]=temp;
max_heapify(a,i,0);
}
}
void display(int a[],int n)
{
int i;
printf("\n");
for(i=0;i<n;i++)
printf("%d ", a[i]);
}
int main()
{
freopen("input.txt","r",stdin);
int a[100000],n=0;
while(scanf("%d",&a[n++])==1);
n--;
display(a,n);
build_max_heap(a,n);
display(a,n);
heap_sort(a,n);
display(a,n);
return 0;
}