简单堆排序

简单堆排序

 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <ctime>
 4 #define Father(N) ((N - 1) >> 1)
 5 #define Left(N) ((N << 1) + 1)
 6 #define Right(N) ((N + 1) << 1)
 7 using namespace std;
 8 
 9 #define VectorMax 10
10 int vector[VectorMax];
11 void heapSort(int *vector, const int length);
12 void print(int *vector, const int length);
13 int main()
14 {
15     srand(time(NULL));
16     for (int i = 0; i < VectorMax; i++)
17         vector[i] = rand() % 1000;
18     heapSort(vector, VectorMax);
19     return 0;
20 }
21 
22 void print(int *vec, int length) 
23 {
24     for (int i = 0; i < length; i++)
25         cout << vec[i] << " ";
26     cout << endl;
27 }
28 void swap(int &a, int &b)
29 {
30     int tmp = a;
31     a = b;
32     b = tmp;
33 } /*build Heap */ 
34 void buildHeap(int *vec, int length)
35 {
36     for (int i = 1; i < length; i++) {
37         int N = i;
38         while (N > 0) {
39             int father = Father(N);
40             if (vec[father] > vec[N])
41                 swap(vec[father], vec[N]);
42             N = father;
43         }
44     }
45 }                /*adjust Heap */
46 
47 void adjustHeap(int *vec, const int length)
48 {
49     int N = 0;
50     int top = vec[0];
51     while (N < length && Left(N) < length) {
52         const int left = Left(N), right = Right(N);
53         if (right >= length) {    /*if right exceed length */
54             if (top > vec[left])
55                 vec[N] = vec[left], N = left;
56             break;
57         }
58         if (vec[left] > top && vec[right] > top)    /*select the small one */
59             break;
60         int nextN = vec[left] < vec[right] ? left : right;
61         vec[N] = vec[nextN];
62         N = nextN;
63     } vec[N] = top;
64 }
65 void heapSort(int *vec, const int length)
66 {
67     buildHeap(vec, length);
68     for (int i = length - 1; i > 0; i--) {    /*swap vec[0] and vec[heap_size-1] */
69         swap(vec[0], vec[i]);    /*each for, the length of vec subtract 1 */
70         adjustHeap(vec, i);
71     } print(vec, length);
72 }

 

posted @ 2014-05-01 16:03  搬砖程序员带你飞  阅读(285)  评论(0编辑  收藏  举报