因为大二时候上数据结构堆排序这没有好好听。但是后面一直用sort,都忘记这事了,现在来补一下堆排序,ps:采用模板是想对字符串也进行排序,结果发现string 并没有重载"<“与”>"运算符。才发现自己是只会c with stl。
代码:
class headsort
{
private:
std::vector<T> ans;
public:
headsort(std::vector<T> a) : ans(a)
{
std::cout << "constructor " << std::endl;
}
void Sort()
{
//1.初始化大根堆
for (int i = ans.size() / 2 - 1; i >= 0; --i)
{
std::cout << "初始化堆" <<std::endl;
HeapAdjust(i,ans.size());
}
//2. 调整堆结构
for (int i = ans.size() - 1; i > 0; --i)
{
std::cout << "调整堆" << std::endl;
swap(0, i);
HeapAdjust(0,i);
}
}
void HeapAdjust(int parent,int length)
{
int child = parent * 2 + 1;
T temp = ans[parent]; //取出当前元素
for (; child < length; child=child*2+1)
{
//如果右节点存在且大于左节点,将子节点调整为右节点
if (child + 1 < length && ans[child + 1] > ans[child])
++child;
//如果子节点大于父节点,将字节点赋给父节点,无需交换
if (ans[child] > temp)
{
ans[parent] = ans[child];
parent = child;
}
else
break;
}
ans[parent] = temp;
}
void swap(int i, int j)
{
T temp = ans[i];
ans[i] = ans[j];
ans[j] = temp;
}
void show()
{
for (auto &x : ans)
{
std::cout<<x<<std::endl;
}
std::cout << "\n";
}
~headsort()
{
std::cout << "析构函数" << std::endl;
}
};