数据结构-堆
堆排序代码:
#pragma once #include <vector> class HeapSort { public: void sort(std::vector<int>& seq) { // 构建大顶堆 for (int i = seq.size() / 2 - 1; i >= 0; --i) { adjustHeap(seq, i, seq.size()); } // 逐渐调整 for (int i = 0; i < seq.size()-1; ++i) { std::swap(seq[0], seq[seq.size()-i-1]); adjustHeap(seq, 0, seq.size() - i - 1); } } void adjustHeap(std::vector<int>& seq, int index, int len) { int temp = seq[index]; for (int k = index * 2 + 1; k < len-1; k = k * 2 + 1) { if (seq[k] < seq[k + 1]) { k++; } if (seq[k] > temp) { seq[index] = seq[k]; index = k; } else { break; } } seq[index] = temp; } };
测试:
int main() { std::vector<int> seq{ 9,8,7,6,5,4,3,2,1 }; HeapSort heapSort; heapSort.sort(seq); for(auto s: seq) { cout << s << " "; } cout << endl; }
一篇写的很详细的博客 :https://www.jianshu.com/p/6b526aa481b1
https://www.cnblogs.com/chengxiao/p/6129630.html
后续再补充插入,删除节点代码