-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapsort
56 lines (49 loc) · 923 Bytes
/
heapsort
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
//
// main.c
// heap sort
//
// Created by 毛遵杰 on 2019/12/11.
// Copyright © 2019 毛遵杰. All rights reserved.
//
#include<stdio.h>
int a[100];
void Exchange(int i,int n){
int temp;
temp = a[i];
a[i] = a[n];
a[n] = temp;
}
void Created(int n)
{
if(n == 2){
if(a[0] > a[1]){
printf("%d %d\n",a[0],a[1]);
}
else
printf("%d %d\n",a[1],a[0]);
return;
}
int i;
for(i = n/2-1;i >= 0; i--)
{
if(a[2*i+1] > a[i] && 2*i+1 < n)
Exchange(i,2*i+1);
if(a[2*i+2] > a[i] && 2*i+2 < n)
Exchange(i,2*i+2);
}
int t;
t = a[0];
a[0] = a[n-1];
a[n-1] = t;
printf("%d ",a[n-1]);
Created(n-1);
}
int main()
{
int n=10;
for(int j =0; j <n; j++)
{
scanf("%d",&a[j]); //enter 12,2,16,30,28,10,16,20,6,18
Created(n);
return 0;
}