堆排序(未调好)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<stdbool.h>

void Swap(int *nums, int a, int b)
{
    int midNum = nums[a];
    nums[a] = nums[b];
    nums[b] = midNum;
}
void Heapify(int *nums, int numsSize,int idx)
{
    int left = 2 * idx + 1;
    int right = 2 * idx + 2;
    while (left < numsSize ) {
        int childMax = right < numsSize && nums[left] > nums[right] ? left : right;
        int bothMax = nums[childMax] > nums[idx] ? childMax : idx;
        if (bothMax == idx) {
            break;
        }
        Swap(nums, idx, childMax);
        idx = childMax;
        left = 2 * idx + 1;
        right = 2 * idx + 2;
    }
}
void HeapInsert(int *nums, int numsIdx)
{
    int index = numsIdx;
    while (nums[index] > nums[index / 2]) {
        if (nums[index] > nums[index / 2]) {
            Swap(nums, index / 2, index);
        }
        index = index / 2;
    }
}
int main()
{
    int nums[] = { 3, 2, 1, 5, 6, 4 };
    for (int i = 0; i < 6; i++) {
        HeapInsert(nums, i);
    }
    for (int i = 0; i < 6; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");
    int numsSize = 6;
    for (int i = 0; i < 6; i++) {
        printf("%d ", nums[0]);
        numsSize--;
        Swap(nums, 0, numsSize);
        Heapify(nums, numsSize, 0);
    }
    getchar();
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
堆排序是一种基于堆的排序算法,它将待排序序列构建成一个小根堆或大根堆,然后依次将堆顶元素与堆中最后一个元素交换位置,并将堆的大小减1,重复执行该操作直到堆为空。由于小根堆或大根堆的特性,每次交换后堆的性质仍然得以满足,因此可以保证最终得到一个有序序列。 具体来说,堆排序的过程如下: 1. 将待排序序列构建成一个小根堆或大根堆。 2. 将堆顶元素与堆中最后一个元素交换位置,并将堆的大小减1。 3. 对新的堆顶元素进行向下调整操作,使其重新满足小根堆或大根堆的性质。 4. 重复执行步骤2和步骤3,直到堆为空。 堆排序的时间复杂度为O(nlogn),其中n为待排序序列的长度。由于堆排序的操作都是在原地进行的,因此它不需要额外的存储空间,是一种空间复杂度为O(1)的排序算法。 以下是一个使用小根堆进行升序排序的例子: ```python def heap_sort(nums): # 构建小根堆 def heapify(nums, n, i): smallest = i left_child = 2 * i + 1 right_child = 2 * i + 2 if left_child < n and nums[left_child] < nums[smallest]: smallest = left_child if right_child < n and nums[right_child] < nums[smallest]: smallest = right_child if smallest != i: nums[i], nums[smallest] = nums[smallest], nums[i] heapify(nums, n, smallest) n = len(nums) # 构建小根堆 for i in range(n // 2 - 1, -1, -1): heapify(nums, n, i) # 依次将堆顶元素与堆中最后一个元素交换位置,并将堆的大小减1 for i in range(n - 1, 0, -1): nums[0], nums[i] = nums[i], nums[0] heapify(nums, i, 0) return nums ``` 对于输入序列[3, 5, 2, 8, 1, 7, 4, 6],经过堆排序后,得到的有序序列为[1, 2, 3, 4, 5, 6, 7, 8]。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值