排序算法4---堆排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shanghx_123/article/details/83348470

堆排序

基本思想: 大堆对应升序序列,小堆对应降序队列,我们从最后一个非叶子结点建堆,步骤如下:
⑴ 将堆顶元素与当前最大堆的最后一个节点交换
⑵ 最大堆节点-1,即调整剩下的n-1个节点
⑶ 从堆顶继续向下调整,试之满足最大堆,循环⑴和⑵ ,直至剩下一个节点。
时间复杂度: NlogN
稳 定 性 :不稳定
适用场景:topK等问题

void AdjustDown(int *arr, int root, int size)//建大堆
{
 int parent = root;
 int child = parent * 2 + 1;
 while (child < size)
 {
   //保证child指向较大节点
   if (child + 1 < size && arr[child + 1] > arr[child])
     child += 1;
   if (arr[child] > arr[parent])
   {
     std::swap(arr[child], arr[parent]);
     parent = child;//下滤
     child = parent * 2 + 1;
   }
   else
     break;
 }
}
//堆排序递归
void HeapSort(int *arr, int size)
{
 assert(arr && size > 1);
 //从最后一个非叶子节点建堆
 for (int idx = (size - 2) / 2; idx >= 0; --idx)
 {
   AdjustDown(arr, idx, size);//下滤调整
 }
 int end = size - 1;
 while (end > 0)
 {
   //堆顶与最后一个节点交换,升序
   std::swap(arr[0], arr[end]);
   AdjustDown(arr, 0, end);//下滤调整
   --end;
 }
}

猜你喜欢

转载自blog.csdn.net/shanghx_123/article/details/83348470
今日推荐