基本排序方法及分析(七):HeapSort 堆排序
1
/**//*
2
* 堆排序
3
* O(nlgn)
4
*/
5
6
#include <iostream>
7
#include <cstdlib>
8
9
#define LEFT(i) (2*i+1)
10
#define RIGHT(i) (2*i+2)
11
#define PARENT(i) ( (i-1)/2 )
12
13
using namespace std;
14
15
//交換兩個元素值
16
void swap(int& a, int& b);
17
//輸出數組元素
18
void print(int*a, int n);
19
20
//保持堆性質,當左右子樹都是堆時,但a[i]可能違反堆性質時,調整成堆
21
void MaxHeapify(int *a, int i, int n)
22

{
23
int left = LEFT(i);
24
int right = RIGHT(i);
25
int largest = i;
26
27
if(left < n && a[left] > a[largest] )
28
largest = left;
29
if(right < n && a[right] > a[largest])
30
largest = right;
31
if(largest != i)
32
{
33
swap(a[i],a[largest]);
34
MaxHeapify(a,largest,n);
35
}
36
}
37
38
//創建堆
39
void BuildMaxHeap(int* a, int n)
40

{
41
//從有子樹的開始
42
for(int i = PARENT(n-1); i >= 0; i--)
43
{
44
MaxHeapify(a,i,n);
45
}
46
}
47
48
void HeapSort(int *a, int n)
49

{
50
//創建堆
51
BuildMaxHeap(a, n);
52
for(int i = n -1; i >= 1; i--)
53
{
54
//把最大元素放在最后,下一步不予考慮
55
swap(a[i],a[0]);
56
MaxHeapify(a,0,i); //這里不是MaxHeapify(a,0,i-1);
57
}
58
}
59
60
61
//交換兩個元素值
62
void swap(int& a , int& b)
63

{
64
int temp = a;
65
a = b;
66
b = temp;
67
}
68
69
//打印數組
70
void print(int* a , int n)
71

{
72
for(int i = 0; i < n ; i++)
73
cout << a[i] << ",";
74
cout << endl;
75
}
76
77
78
int main()
79

{
80
const int N = 10;
81
int a[N] =
{4,1,3,2,16,9,10,14,8,7};
82
83
print(a,N);
84
85
HeapSort(a,N);
86
87
print(a,N);
88
89
system("pause");
90
return 0;
91
}

/**//*2
* 堆排序3
* O(nlgn)4
*/ 5
6
#include <iostream> 7
#include <cstdlib>8

9
#define LEFT(i) (2*i+1)10
#define RIGHT(i) (2*i+2) 11
#define PARENT(i) ( (i-1)/2 )12

13
using namespace std; 14

15
//交換兩個元素值 16
void swap(int& a, int& b);17
//輸出數組元素 18
void print(int*a, int n);19

20
//保持堆性質,當左右子樹都是堆時,但a[i]可能違反堆性質時,調整成堆 21
void MaxHeapify(int *a, int i, int n)22


{23
int left = LEFT(i);24
int right = RIGHT(i); 25
int largest = i; 26
27
if(left < n && a[left] > a[largest] )28
largest = left; 29
if(right < n && a[right] > a[largest])30
largest = right;31
if(largest != i)32

{33
swap(a[i],a[largest]);34
MaxHeapify(a,largest,n);35
}36
}37

38
//創建堆 39
void BuildMaxHeap(int* a, int n)40


{41
//從有子樹的開始 42
for(int i = PARENT(n-1); i >= 0; i--)43

{44
MaxHeapify(a,i,n);45
}46
}47

48
void HeapSort(int *a, int n)49


{50
//創建堆 51
BuildMaxHeap(a, n); 52
for(int i = n -1; i >= 1; i--)53

{54
//把最大元素放在最后,下一步不予考慮 55
swap(a[i],a[0]);56
MaxHeapify(a,0,i); //這里不是MaxHeapify(a,0,i-1); 57
}58
}59

60

61
//交換兩個元素值 62
void swap(int& a , int& b)63


{64
int temp = a;65
a = b;66
b = temp;67
}68

69
//打印數組 70
void print(int* a , int n)71


{72
for(int i = 0; i < n ; i++)73
cout << a[i] << ",";74
cout << endl;75
}76

77

78
int main()79


{80
const int N = 10; 81

int a[N] =
{4,1,3,2,16,9,10,14,8,7}; 82
83
print(a,N);84
85
HeapSort(a,N);86
87
print(a,N); 88
89
system("pause");90
return 0;91
} posted on 2010-01-18 15:45 幸運草 閱讀(669) 評論(1) 編輯 收藏 引用 所屬分類: Algorithms

