堆排序法利用二叉树最大堆实现对数字的排序。其排序的时间为O(nlgn)。本文给出了一个堆排序算法的简单实现(利用C++),希望对大家有用。

该排序算法主要利用了二叉树最大堆的以下属性:

属性定义:二叉树最大堆的任意节点的值小于等于其父节点的值;

根据该定义,便可以按照以下步骤轻松实现堆排序算法:

  1. 利用输入的数组建立一个最大堆,则最大堆的根节点为数组元素中的最大值;
  2. 将根节点的值和最后一个节点值进行交换(实际上就是将最大值存入数组的最后一个位置中)
  3. 利用堆中剩余的所有节点再次建立一个二叉树最大堆;然后进行第一和第二步操作;

这样,每完成一次操作,堆中的节点便减少一个;由于时间关系,该算法的实现细节不予讨论,一切都在代码中:

1 #include <iostream>
2 #include <algorithm>
3
4  using namespace::std;
5
6  //对排序实现类的定义
7 class HeapSort
8 {
9 public:
10 HeapSort(int *pArray = NULL, int nArraySize = 0);
11 ~HeapSort();
12 public:
13 int *m_pA;
14 int m_nHeapSize;
15 public:
16 void Sort();
17 private:
18 int LeftChild(int node);
19 int RightChild(int node);
20 void MaxHeapify(int nIndex);
21 void BuildMaxHeap();
22 };
23
24 //对排序类成员函数的实现
25 HeapSort::HeapSort( int *pArray, int nArraySize )
26 {
27 m_pA = pArray;
28 m_nHeapSize = nArraySize;
29 }
30
31 HeapSort::~HeapSort()
32 {
33 }
34
35 int HeapSort::LeftChild(int node)
36 {
37 return 2*node + 1;
38 }
39
40 int HeapSort::RightChild(int node)
41 {
42 return 2*node + 2;
43 }
44
45 void HeapSort::MaxHeapify(int nIndex)
46 {
47 int nLeft = LeftChild(nIndex);
48 int nRight = RightChild(nIndex);
49
50 int nLargest = nIndex;
51
52 if( (nLeft < m_nHeapSize) && (m_pA[nLeft] > m_pA[nIndex]) )
53 nLargest = nLeft;
54
55 if( (nRight < m_nHeapSize) && (m_pA[nRight] > m_pA[nLargest]) )
56 nLargest = nRight;
57
58 if ( nLargest != nIndex )
59 {
60 swap<int>(m_pA[nIndex], m_pA[nLargest]);
61 MaxHeapify(nLargest);
62 }
63 }
64
65 void HeapSort::BuildMaxHeap()
66 {
67 if( m_pA == NULL )
68 return;
69
70 for( int i = (m_nHeapSize - 1)/2; i >= 0; i-- )
71 {
72 MaxHeapify(i);
73 }
74 }
75 void HeapSort::Sort()
76 {
77 if( m_pA == NULL )
78 return;
79 if( m_nHeapSize == 0 )
80 return;
81
82 BuildMaxHeap();
83 for( int i = m_nHeapSize - 1; i > 0; i-- )
84 {
85 swap<int>(m_pA[i], m_pA[0]);
86 m_nHeapSize -= 1;
87 MaxHeapify(0);
88 }
89 }
90
91 //该类在主函数中的使用
92 int main()
93 {
94 //int A[14] = { 27,17,3,16,13,10,1,5,7,12,4,8,9,0 };
95 int A[10] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
96 HeapSort mySort(A,10);
97 mySort.Sort();
98 for( int i = 0; i < 14; i++ )
99 cout << A[i] << " ";
100 cout << endl;
101
102 }

计算结果如下图:

原创文章,转载请注明出处

posted on 2011-05-16 17:46  cylee025  阅读(1955)  评论(0编辑  收藏  举报