-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapsort.c
78 lines (74 loc) · 956 Bytes
/
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
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
heap(int A[],int n,int i)
{
int j=1,left,right,max;
max=i;
left=2*i;
right=2*j+1;
}
void insert(int A[],int n)
{
heap(A,n,1);
int t,i=n-1;
t=A[n-1];
while(i>1 && t>A[i/2])
{
A[i]=A[i/2];
i=i/2;
}
}
int deleting(int A[],int n)
{
heap(A,n,1);
int i,j,t;
t=A[1];
A[1]=A[n-1];
A[n-1]=t;
i=1;
j=2*i;
while(j<n-2)
{
if(A[j+1]>A[j])
{
j=j+1;
}
if(A[i]<A[j])
{
swap(&A[i],&A[j]);
i=j;
j=2*j;
}
else
break;
}
return t;
}
void main()
{
int n,i;
int A[]= {0,15,2,3,4,17,9,6,44,71};
n=sizeof(A)/sizeof(A[0]);
// printf("%d\n",n);
i=1;
// heap(A,n,i);
for(i=2;i<n;i++)
{
insert(A,i);
}
for(i=n-2;i>0;i++)
{
deleting(A,n);
}
for(i=1;i<n;i++)
{
heap(A,n,i);
printf("%d\n",A[i]);
}
}