forked from dscgecbsp/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapsort.c
99 lines (92 loc) · 1.68 KB
/
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*Program to demonstrate the heap sort algorithm to sort an array using max heap*/
#include<stdio.h>
#include<math.h>
main()
{
int a[100],n,i,lb,ub;
void swap(int*,int*);
void heapsort(int[],int,int);
printf("Enter number of elements:");
scanf("%d",&n);
lb=0;
ub=n-1;
printf("Enter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,lb,ub);
printf("The sorted array is:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
void heapsort(int a[],int lb,int ub)
{
int i;
void create_heap(int[],int,int,int,int);
void del_heap(int[],int,int,int);
for(i=lb;i<=ub;i++)
{
create_heap(a,i,a[i],lb,ub);
}
i=ub;
while(i>=lb)
{
del_heap(a,i+1,lb,ub);
i--;
}
}
void create_heap(int a[],int heapsize,int data,int lb,int ub)
{
int i,p;
int parent(int);
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}
void del_heap(int a[],int heapsize,int lb,int ub)
{
int data,i,l,r,max_child;
int left(int);
int right(int);
swap(&a[lb],&a[heapsize-1]);
i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
else
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child])
break;
swap(&a[i],&a[max_child]);
i=max_child;
}
}
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
int left(int i)
{
return 2*i+1;
}
int right(int i)
{
return 2*i+2;
}