基本排序方法及分析(七):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
13using namespace std;
14
15//交换两个元素值
16void swap(int& a, int& b);
17//输出数组元素
18void print(int*a, int n);
19
20//保持堆性质,当左右子树都是堆时,但a[i]可能违反堆性质时,调整成堆
21void 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//创建堆
39void 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
48void 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//交换两个元素值
62void swap(int& a , int& b)
63{
64 int temp = a;
65 a = b;
66 b = temp;
67}
68
69//打印数组
70void print(int* a , int n)
71{
72 for(int i = 0; i < n ; i++)
73 cout << a[i] << ",";
74 cout << endl;
75}
76
77
78int 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
13using namespace std;
14
15//交换两个元素值
16void swap(int& a, int& b);
17//输出数组元素
18void print(int*a, int n);
19
20//保持堆性质,当左右子树都是堆时,但a[i]可能违反堆性质时,调整成堆
21void 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//创建堆
39void 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
48void 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//交换两个元素值
62void swap(int& a , int& b)
63{
64 int temp = a;
65 a = b;
66 b = temp;
67}
68
69//打印数组
70void print(int* a , int n)
71{
72 for(int i = 0; i < n ; i++)
73 cout << a[i] << ",";
74 cout << endl;
75}
76
77
78int 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}
转载请注明出处: http://www.cnblogs.com/liyuxia713/