排序--堆排序

数组的堆排序

#include<stdio.h>
//对数组进行堆排序
//数组要升序,则要建大堆
//数组要降序,建小堆
typedef int datatype;
void Swap(datatype* array, int left, int right) {
 int tmp = array[left];
 array[left] = array[right];
 array[right] = tmp;
}
//大堆,向下调整
void bigshiftdown(datatype* array, int size, int parent) {  //parent表示起始调整位置
 //先选择左孩子
 int child = 2 * parent + 1;
 while (child < size) {
  //判断俩孩子那个更大
  if (child + 1 < size && array[child] < array[child + 1]) {   
   child++;
  }
  if (array[child] > array[parent]) {
   //交换父节点跟子节点的值
   Swap(array, child, parent);
   //更新,继续交换
   //直至小于父节点的值或者大于size
   parent = child;
   child = 2 * parent + 1;
  }
  else {
   break;
  }
 }
}
//对数组进行堆排序
void HeapSort(int* array, int n) {
 //建堆
 //i选择最后一个非叶子节点,依次遍历此节点之前的所有节点
 for (int i = (n - 2) / 2; i >= 0; i--) {
  bigshiftdown(array, n, i);
 }
 int size = n;
 while (size > 1) {
  //循环尾删
  Swap(array, 0, size - 1);
  size--;
  bigshiftdown(array, size, 0);
 }
}
void test() {
 int array[11] = { 23,45,78,65,13,44,12,32,56,9,11 };
 int n = 11;
 HeapSort(array, n);
 for (int i = 0; i < n; i++) {
  printf("%d ", array[i]);
 }
}
int main() {
 test();
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值