博客
关于我
排序——堆排序
阅读量:687 次
发布时间:2019-03-17

本文共 1684 字,大约阅读时间需要 5 分钟。

#include 
#include
#include
using namespace std;// 堆排序的主要算法思想是将一个数组经过一系列操作,变成一个堆结构(大顶堆),然后逐步将这个堆结构转换成有序数组。// 堆排序的关键操作包括调整(HeapAdjust)和排序(HeapSort)void HeapAdjust(int arr[], int i, int length) { int child = 2 * i + 1; while (2 * i + 1 < length) { // 确定子节点的位置,并检查右边的子节点是否更大 if (child < length - 1 && arr[child + 1] > arr[child]) { child++; } if (arr[i] < arr[child]) { // 交换父节点和较大的子节点 int temp = arr[i]; arr[i] = arr[child]; arr[child] = temp; } else { break; } i = child; child = 2 * i + 1; }}void HeapSort(int arr[], int length) { // 先调整前半部分为大顶堆 for (int i = length / 2 - 1; i >= 0; --i) { HeapAdjust(arr, i, length); } // 结束后,最大值在数组开头 // 从最后一个元素开始调整,并不断缩小范围 for (int i = length - 1; i > 0; --i) { // 将当前最大值移动到正确位置 int temp = arr[i]; arr[i] = arr[0] ^ arr[i]; arr[0] = temp; arr[i] = arr[0] ^ arr[i]; HeapAdjust(arr, 0, i); }}int main() { int a[100]; int count = 0; int size = 0; // 读取输入 do { size++; scanf("%d", &a[size]); count++; } while (a[size] != 0); // 调用堆排序算法 HeapSort(a, size); // 输出结果 for (int i = 1; i < size; i++) { printf("%d ", a[i]); }}

上述代码展示了一个实现堆排序的C语言程序,其主要目标是对一个数组进行排序。堆排序的思路是将数组先构造成一个大顶堆,然后利用堆的性质逐步将最大值移动到正确的位置,最终完成排序。

程序包含两个主要函数:

  • HeapAdjust:用于调整大顶堆结构
  • HeapSort:主要排序函数,通过多次HeapAdjust实现排序
  • 代码结构清晰,注释详细,并包含了一个示例,展示了如何使用该排序函数进行实际数据处理。程序的注意事项包括:

    • 数据输入处理需要注意数组的起始位置
    • 调用函数时需要确保参数正确
    • HeapAdjust函数的递归深度需要控制在合理范围内以避免栈溢出

    代码保留了调试信息(如评论),但用户可以根据实际需求选择是否保留

    转载地址:http://rofhz.baihongyu.com/

    你可能感兴趣的文章
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>