其他分享
首页 > 其他分享> > 堆排序 比较简单的做法

堆排序 比较简单的做法

作者:互联网

最大堆 进行升序排列

步骤

代码

#include <iostream>

void maxHeaptify(int a[], int s, int e)
{
  int c = s;
  int tmp = a[c];
  int l = 2*c + 1;

  for (;l <= e; c = l,l = 2*l+1)
  {
    // l < e very important, otherwise the last already sorted one will be re-calculated
    if (l < e && a[l] < a[l+1]) l++;
    if (a[c] > a[l]) break;
    else
    {
      a[c] = a [l];
      a[l] = tmp;
    }
  }
}

void heapSort(int a[], int n)
{
  // firstly, build heap tree
  for (int i = (n-1)/2; i >= 0; --i)
  {
    maxHeaptify(a, i, n-1);
  }

  for (int i = 0; i < n; ++i)
  {
    std::cout << a[i] << " ";
  }
  std::cout << std::endl;

  for (int i = n-1; i >0; --i)
  {
    int tmp = a[0];
    a[0] = a[i];
    a[i] = tmp;
    maxHeaptify(a, 0, i-1);
  }
}


int main()
{
  int a[] = {2, 3, 4, 5, 6, 2, 3, 4, 1};
  int length = sizeof(a)/sizeof(a[0]);
  heapSort(a, length);

  for (int i = 0; i < length; ++i)
  {
    std::cout << a[i] << " ";
  }
  std::cout << std::endl;

  return 0;
}

小顶堆本地sharpen文件夹也试了一遍。

结果

在这里插入图片描述

标签:tmp,比较简单,int,堆排序,++,length,maxHeaptify,做法,sizeof
来源: https://blog.csdn.net/victory_castle/article/details/105899918