-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathheap_sort.c
More file actions
58 lines (49 loc) · 722 Bytes
/
Copy pathheap_sort.c
File metadata and controls
58 lines (49 loc) · 722 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
#include<stdio.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
void maxheapify(int A[],int n,int i)
{
int l=2*i;
int r=2*i+1;
int largest=i;
if(l<n && A[l]>A[i])
largest = l;
else
largest=i;
if(r<n && A[r]>A[largest])
largest=r;
if(largest!=i)
{
swap(&A[i],&A[largest]);
maxheapify(A,n,largest);
}
}
void build(int A[], int n)
{
for(int i=n/2-1; i>=0; i--)
maxheapify(A,n,i);
}
void heapsort(int A[], int n)
{
build(A,n);
for(int i=n-1; i>=0; i--)
{
swap(&A[i],&A[0]);
maxheapify(A,i,0);
}
}
int main()
{
int n;
scanf("%d",&n);
int A[n];
for(int i=0; i<n ;i++)
scanf("%d ",&A[i]);
heapsort(A,n);
for(int i =0; i<n;i++)
printf("%d ",A[i]);
}