堆排序是一種常見的排序算法,其時間複雜度爲O(logN),重要思想爲建堆取極值,根據需求進行排序,以下圖:
算法
值得思考的是,二次建堆的過程當中,其實是沒有必要將全部元素都進行下調,只須要將根進行下調:
ide
實現代碼以下:
函數
template <class T>//創建仿函數模板知足排序需求 struct CompMax { bool operator()(const T& a, const T& b) { return a > b; } }; template <class T> struct CompMin { bool operator()(const T& a,const T& b) { return a < b; } }; template <class T ,class Com = CompMax<T> > static void HeapSort(vector<T>&list) { size_t size = list.size(); GetHeap<T>(list, size); swap(list[0], list[size - 1]); while (--size > 1) { adjustdown<T>(0, size, list); swap(list[0], list[size - 1]); } } template <class T,class Com = CompMax<T> > void adjustdown(int index, size_t size, vector<T>&list) { Com comp; size_t parent = index; size_t child = parent * 2 + 1; while (child < size) { if (child + 1 < size) child = child = comp(list[child], list[child + 1]) ? child : child + 1; if (!comp(list[parent], list[child])) { std::swap(list[child], list[parent]); parent = child; child = parent * 2 + 1; } else break; } } template <class T ,class Com = CompMax<T> > static void GetHeap(vector<int>&list, size_t size) { size_t parent = (size - 2) / 2; int begin = parent; Com comp; while (begin >= 0) { size_t child = parent * 2 + 1; while (child<size) { if (child + 1<size) child = child = comp(list[child], list[child + 1]) ? child : child + 1; if (!comp(list[parent], list[child])) { swap(list[child], list[parent]); parent = child; child = parent * 2 + 1; } else break; } parent = --begin; } }
若有不足,但願指正,有疑問也但願提出
3d