首页 > 代码库 > 堆排序的基本实现

堆排序的基本实现

 1 class Heap{ 2 private: 3     int m[1000]; 4     int size; 5 public: 6     Heap(int s) :size(s){} 7     Heap(int *num, int s) :size(s){  8         for (int i = 0; i < size; i++) 9             m[i] = num[i]; 10 11     }12     int parent(int i)13     {14         return i / 2;15     }16     int left(int i)17     {18         return i * 2 + 1;19     }20     int right(int i)21     {22         return i * 2 + 2;23     }24     void Heapify(int i)25     {26         int mx = i;27         int l = left(i);28         int r = right(i);29         if (l<size && m[l] > m[mx])30             mx = l;31         if (r<size && m[r] > m[mx])32             mx = r;33         if (i != mx){34             swap(m[mx], m[i]);35             Heapify(mx);36         }37     }38 39     void BuildHeap()40     {41         for (int i = size / 2; i >= 0; i--)42             Heapify(i);43     }44 45     void HeapSort()46     {47         cout << "Hello" << endl;48         cout << size << endl;49         while (size > 1)50         {51             cout << "Sorting_out:" << m[0] << endl;52             swap(m[0], m[size - 1]);53             size--;54             Heapify(0);55         }56     }57     int get(int i)58     {59         return m[i];60     }61 62 63 };

 

堆排序的基本实现