-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.c
87 lines (65 loc) · 1.29 KB
/
heap.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
#include<stdio.h>
#include<stdlib.h>
int n,i,a[10],left,right;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void heapify(int a[],int n,int i)
{
int largest;
largest=i;
left=2*i;
right=(2*i)+1;
if(left<n && a[left]>a[largest]) //if left is largest than root
{
largest=left;
}
if(right<n && a[right]>a[largest]) //if right is largest than root
{
largest=right;
}
//if the root is not the largest
if(largest!=i)
{
swap(&a[largest],&a[i]);
heapify(a,n,largest);
}
}
void heapsort(int a[],int n)
{
for(i=n/2;i>=1;i--)
{
heapify(a,n,i);
}
//for heap sort
for(i=n;i>=1;i--)
{
swap(&a[i],&a[1]);
heapify(a,i,1);
}
}
void printarray(int a[],int n)
{
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
}
void main()
{
printf("enter the no of elements\n");
scanf("%d",&n);
printf("enter the elements\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
//heap sort
heapsort(a,n);
printf("the sorted array is\n");
printarray(a,n);
}