-
Notifications
You must be signed in to change notification settings - Fork 1
/
heap_sort.c
70 lines (62 loc) · 1.08 KB
/
heap_sort.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
67
68
69
70
#include <stdio.h>
void heapify(int A[],int n,int i)
{
int L,R,largest;
L=2*i+1;
R=2*i+2;
largest=i;
if(L<n && A[L]>A[largest])
{
largest=L;
}
if(R<n && A[R]>A[largest])
{
largest=R;
}
if(largest!=i)
{
int temp=A[i];
A[i]=A[largest];
A[largest]=temp;
heapify(A,n,largest);
}
}
void BuildMaxHeap(int A[],int n)
{
int i;
for(i=(n/2)-1;i>=0;i--)
{
heapify(A,n,i);
}
}
void HeapSort(int A[],int n)
{
int i;
BuildMaxHeap(A,n);
for(i=n-1;i>0;i--)
{
int temp1=A[0];
A[0]=A[i];
A[i]=temp1;
heapify(A,i,0);
}
}
void main()
{
int A[20],i=0,num;
printf("How many numbers?");
scanf("%d",&num);
printf("Enter the numbers to be sorted: ");
for(i=0;i<num;i++)
{
scanf("%d",&A[i]);
}
// heapify(A,num,i);
//BuildMaxHeap(A,num);
HeapSort(A,num);
printf("Sorted numbers: ");
for (int i = 0; i < num; i++) {
printf("%d ", A[i]);
}
printf("\n");
}