c语言实现堆排序

完成此功能需要四个函数来实现

第一个是交换函数:交换数组中两个数的位置;

第二个是heapinsert:建立大根堆的函数

第三个是heapify函数:假设取走第一个大根堆的数,然后接着建立大根堆

第四个是排序函数:先用heapinsert来建立这个数组的大根堆,然后将第一个数与最后一个数交换,然后在除最后一个数之外的数组进行堆化。


void swap(int* nums, int i, int j) {
    int temp = *(nums + i);
    *(nums + i) = *(nums + j);
    *(nums + j) = temp;
}

void heapinsert(int* nums, int index) {
    while (nums[index] > nums[(index - 1) / 2]) {
        swap(nums, index, (index - 1) / 2);
        index = (index - 1) / 2;
    }
}

void heapify(int* nums, int index, int heapSize) {
    int left = index * 2 + 1;
    int largest = 0;
    while (left < heapSize) {
        largest = left + 1 < heapSize && nums[left] < nums[left + 1] ? left + 1 : left;
        largest = nums[largest] > nums[index] ? largest : index;
        if (largest == index) break;
        swap(nums, largest, index);
        left = index * 2 + 1;
    }
}

void heapsort(int* nums, int numsSize) {

    if (nums == NULL || numsSize < 2) return;
    int heapSize=numsSize-1;
    for ( int i = 0; i < numsSize; i++) {
        heapinsert(nums,i);
    }
    while (heapSize >= 0) {
        swap(nums, 0, heapSize);
        heapSize--;
        heapify(nums, 0, heapSize);
        
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值