/* 調整堆, 向下調整的過程 */
static void heapAdjust(std::vector<int> &vec, int start, int end)
{
int i = start;
while((2*i + 1) < end)
{
int maxIndex = 2*i + 1;
if ((2*i + 2) < end)
{
if (vec[2*i + 2] > vec[maxIndex])
{
maxIndex = 2*i + 2;
}
}
if (vec[maxIndex] > vec[i])
{
int tmp = vec[i];
vec[i] = vec[maxIndex];
vec[maxIndex] = tmp;
}
else
{
break;
}
i = maxIndex;
}
}
/* 建堆,從 vec.size() / 2 - 1開始,選擇子樹及自身最小的節點爲當前的根節點的值,依次處理,直至根節點,全局向上調整,局部向下調整 */
static void buildHeap(std::vector<int>& vec)
{
for (int i = vec.size() / 2 - 1; i >= 0 ; i--)
{
heapAdjust(vec, i, vec.size());
}
}
/* 堆排序, 入口,時間複雜度O(nlogn),大根堆 */
static void heapSort(std::vector<int>& vec)
{
if (vec.empty())
{
return;
}
buildHeap(vec);
for (int i = vec.size() - 1; i > 0; i--)
{
int tmp = vec[i];
vec[i] = vec[0];
vec[0] = tmp;
heapAdjust(vec, 0, i);
}
}