最大堆与堆排序

参考《Introduce to Algorithm》

  1 #ifndef MAX_HEAP_H
  2 #define MAX_HEAP_H
  3
  4 const int MAX_SIZE = 100 + 1 ;
  5
  6 template < typename Type >
  7 class MaxHeap
  8 {
  9     public :
10         MaxHeap();
11         MaxHeap(Type * arr, int size);
12         // ~MaxHeap();
13        
14         void travel();
15         void HeapSort();
16
17     private :
18         Type _arr[MAX_SIZE];
19         int _size;
20
21         void MaxHeapify( int startIndex); // 调整堆
22         void InitBuildMaxHeap(); // 初始建堆
23         void swap(Type & a, Type & b);
24 };
25
26 template < typename Type >
27 MaxHeap < Type > ::MaxHeap()
28 {
29     for ( int i = 0 ; i < MAX_SIZE; i ++ )
30     {
31         _arr[i] = 0 ;
32     }
33     _size = 0 ;
34 }
35
36 template < typename Type >
37 MaxHeap < Type > ::MaxHeap(Type * arr, int size)
38 {
39     if (size > MAX_SIZE)
40     {
41         cerr << " larger than MAX_SIZE " << endl;
42     }
43     for ( int i = 0 ; i < size; i ++ )
44     {
45         _arr[i + 1 ] = arr[i];
46     }
47     _size = size;
48     InitBuildMaxHeap();
49 }
50
51 template < typename Type >
52 void MaxHeap < Type > ::HeapSort()
53 {
54     int tmp = _size;
55     for ( int i = _size; i >= 2 ; i -- )
56     {
57         swap(_arr[ 1 ], _arr[i]);
58         _size -- ;
59         MaxHeapify( 1 );
60     }
61    
62     _size = tmp;
63    
64 }
65
66 template < typename Type >
67 void MaxHeap < Type > ::InitBuildMaxHeap()
68 {
69     for ( int i = _size / 2 ; i >= 1 ; i -- )
70     {
71         MaxHeapify(i);
72     }
73 }
74
75
76
77 template < typename Type >
78 void MaxHeap < Type > ::travel()
79 {   
80     for ( int i = 1 ; i <= _size; i ++ )
81         cout << _arr[i] << " " ;
82
83     cout << endl;
84 }
85
86
87 template < typename Type >
88 void MaxHeap < Type > ::MaxHeapify( int startIndex)
89 {
90     int maxIndex = startIndex;
91     if ( 2 * startIndex <= _size && _arr[startIndex] < _arr[ 2 * startIndex])
92         maxIndex = 2 * startIndex;
93     if ( 2 * startIndex + 1 <= _size && _arr[maxIndex] < _arr[ 2 * startIndex + 1 ])
94         maxIndex = 2 * startIndex + 1 ;
95
96     if (maxIndex != startIndex)
97     {
98         swap(_arr[startIndex], _arr[maxIndex]);
99         MaxHeapify(maxIndex);
100     }
101
102 }
103
104
105 template < typename Type >
106 void MaxHeap < Type > ::swap(Type & a, Type & b)
107 {
108     Type t;
109     t = a;
110     a = b;
111     b = t;
112 }
113
114
115
116
117 #endif


1 #include < iostream >
2 #include " maxHeap.h "
3 using namespace std;
4
5 int main()
6 {
7     int arr[ 9 ] = { 23 , 43 , 74 , 12 , 4 , 69 , 28 , 26 , 32 };
8     MaxHeap < int > obj(arr, 9 );
9     obj.travel();
10     obj.HeapSort();
11     obj.travel();
12
13     return 0 ;
14 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值