-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathheap_Sort.c
106 lines (94 loc) · 1.18 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
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
100
101
102
103
104
105
// HEAP SORT USING ARRAY IMPLEMENTATION
#include<stdio.h>
int a[20],n;
void display()
{
int i;
for(i=0;i<n;i++)
printf ("%d",a[i]);
printf ("\n");
}
void insert(int num,int loc)
{
int parent;
while(loc>0)
{
parent=(loc-1)/2;
if (num<=a[parent])
{
a[loc]=num;
return;
}
a[loc]=a[parent];
loc=parent;
}
a[0]=num;
}
void create_heap()
{
int i;
for(i=0;i<n;i++)
insert(a[i],i);
}
void del_root(int last)
{
int left,right,i,temp;
i=0;
temp=a[i];
a[i]=a[last];
a[last]=temp;
left=2*i+1;
right=2*i+2;
while( right < last)
{
if ( a[i]>=a[left] && a[i]>=a[right] )
return;
if ( a[right]<=a[left] )
{
temp=a[i];
a[i]=a[left];
a[left]=temp;
i=left;
}
else
{
temp=a[i];
a[i]=a[right];
a[right]=temp;
i=right;
}
left=2*i+1;
right=2*i+2;
}
if ( left==last-1 && a[i]<a[left] )
{
temp=a[i];
a[i]=a[left];
a[left]=temp;
}
}
void heap_sort()
{
int last;
for(last=n-1; last>0; last--)
del_root(last);
}
void main()
{
int i;
printf ("\nEnter number of elements :");
scanf ("%d",&n);
for(i=0;i<n;i++)
{
printf ("\nEnter element %d :",i+1);
scanf ("%d",&a[i]);
}
printf ("\nEntered list is :\n");
display();
create_heap();
printf ("\nHeap is :\n");
display();
heap_sort();
printf ("\nSorted list is :\n");
display();
}