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
| #include <iostream>
using namespace std;
void mySwap(int &a,int &b){
int tmp;
tmp = a;
a = b;
b = tmp;
}
//堆调整
void heapAdjuct(int a[],int size,int i){
int lchild = 2*(i+1)-1;
int rchild = 2*(i+1);
int max = i;
if (i<=size/2-1) {
if (lchild<=size-1&&a[lchild]>a[max]) {
max = lchild;
}
if (rchild<=size-1&&a[rchild]>a[max]) {
max = rchild;
}
if (max!=i) {
mySwap(a[i], a[max]);
heapAdjuct(a, size, max);
}
}
}
//初始化堆
void setupNewHeap(int a[],int size){
for (int i=size/2-1; i>=0; i--) {
heapAdjuct(a, size, i);
}
}
void heapSort(int a[],int size){
setupNewHeap(a, size);
for (int i = size-1; i>0; i--) {
mySwap(a[i], a[0]);
heapAdjuct(a,i, 0);
}
}
int main(int argc, const char * argv[]) {
int a[] = {2,3,1,5,6,9,3,4,8};
heapSort(a,9);
for (int i=0; i<9; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
|