-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapsort.c
56 lines (50 loc) · 902 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
#include<stdio.h>
#include<stdlib.h>
void swap(int arr[],int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
void maxheapify(int arr[],int n,int k){
int l=2*k;
int r=2*k+1;
int max=k;
if(l<n && arr[l]>arr[max])
max=l;
if(r<n && arr[r]>arr[max])
max=r;
if(max!=k)
{
swap(arr,k,max);
maxheapify(arr,n,max);
}
}
void buildmaxheap(int arr[],int n)
{
for(int i=n/2;i>=0;i--)
{
maxheapify(arr,n,i);
}
}
void heapsort(int arr[],int n){
buildmaxheap(arr,n);
for (int i = n - 1; i >=0; i--)
{
swap(arr,0,i);
maxheapify(arr, i, 0);
}
}
void print(int arr[],int n)
{
for(int i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
}
void main()
{
int arr[]={5,7,2,1,8,3,9};
heapsort(arr,7);
print(arr,7);
}