-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathHEAPSORT.BAK
59 lines (59 loc) · 996 Bytes
/
HEAPSORT.BAK
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
#include<stdio.h>
#include<conio.h>
#define max 20
void RestoreHeapUp(int *, int);
void RestoreHeapDown(int*, int, int);
int main()
{
int Heap[max], n, i, j;
clrscr();
printf("\n Enter the number of elements :");
scanf("%d", &n);
printf("\n Enter the elements:");
for(i=1;i<=n;i++)
{
scanf("%d", &Heap[i]);
RestoreHeapUp(Heap, i);
}
j=n;
for(i=1;i<=j;i++)
{
int temp;
temp=Heap[1];
Heap[1]=Heap[n];
Heap[n]=temp;
n=n-1;
RestoreHeapDown(Heap, 1, n);
}
n=j;
printf("\n Sorted elements are:");
for(i=1;i<=n;i++)
printf("%4d", Heap[i]);
getch();
return 0;
}
void RestoreHeapUp(int *Heap, int index)
{
int val = Heap[index];
while((index>1) && (Heap[index/2]<val))
{
Heap[index]=Heap[index/2];
index/=2;
}
Heap[index] = val;
}
void RestoreHeapDown(int *Heap, int index, int n)
{
int val = Heap[index];
int j =index*2;
while(j<=n)
{
if((j<n) && (Heap[j]<Heap[j+1]))
j++;
if(Heap[j]<Heap[j/2])
break;
Heap[j/2]=Heap[j];
j=j*2;
}
Heap[j/2]=val;
}