C++ 堆排序算法

 //基本思路:

  //1.把一个数组按下表构造成一个完全二叉树
  //2.找到数组的最后一个元素(最后一个叶子结点),判断它在左子树上还是右子树上
  //3.如果在左子树上,直接拿该结点与它的父结点比较,如果比父结点大,与父结点交换位置
  //4.如果在右子树上,左右子树先比较大小,把大的放在右子树上,再将右子树与父结点比较,把大的放在父节点上
  //5.查找到倒数第二个父结点,重复它的子树的构建堆过程,直到查找到根结点为止。
  //6.把此时的根结点放在数组的最后一位上(此时根结点是该堆的最大值),重复上诉过程,直到排好序为止。

 

#include<iostream>
using namespace std;

#define N 10

void heapsort(int a[], int num)
{
 int temp, i = 0;
 int num0 = num;
 if (num == 0)
 {
  cout << "没有输入数据";
  return;
 }
 if (num == 1)
  return;
 while (num != 1)
 {
  while (num != 1)
  {
   if (num % 2 == 0)
   {
    if (a[num - 1] >= a[num / 2 - 1])
    {
     temp = a[num - 1];
     a[num - 1] = a[num / 2 - 1];
     a[num / 2 - 1] = temp;
    }
   }
   else
   {
    if (a[num - 1] <= a[num - 2])
    {
     temp = a[num - 2];
     a[num - 2] = a[num - 1];
     a[num - 1] = temp;
    }
    if (a[num - 1] >= a[num / 2 - 1])
    {
     temp = a[num - 1];
     a[num - 1] = a[num / 2 - 1];
     a[num / 2 - 1] = temp;
    }
   }
   num = (num / 2 - 1) * 2 + 1;
  }
  i++;
  temp = a[0];
  a[0] = a[num0 - i];
  a[num0 - i] = temp;
  num = num0 - i;
 }
}


int main()
{
 int a[N] = { 67, 65, 77, 38, 97, 3, 33, 49, 50, 42 };
 int i;
 heapsort(a, N);
 for (i = 0; i < N; i++)
 {
  cout << a[i] << " ";
 }
 cout << endl;
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值