堆排序C语言实现

本文详细介绍了如何在C语言中使用大顶堆数据结构实现堆排序算法,包括建堆、调整堆和排序过程的步骤。通过示例代码展示了从数组中对10个元素进行升序排序的过程。
摘要由CSDN通过智能技术生成

//数组抽象为堆排序

HeapSort.h

#pragma once
#include<stdio.h>
#include<assert.h>
typedef int SortDataType;
void HeapSort(SortDataType* a, int num);
void AdjustDown(SortDataType* a, int n, int size);
void Swap(SortDataType* a, SortDataType* b);

HeapSort.c

#include"heapsort.h"
//升序排列
//建大堆
void Swap(SortDataType* a, SortDataType* b)//多次交换
{
    assert(a && b);
    SortDataType mid = *a;
    *a = *b;
    *b = mid;
}
void AdjustDown(SortDataType* a, int n,int size)//向下建堆能用到,调整能用到
{

   assert(a);
    int parent = n;
    int bigchild = n * 2 + 1;
    while (bigchild < size)
    {
        if (bigchild+1<size&&a[bigchild] < a[bigchild + 1])
            bigchild++;
        if (a[bigchild] > a[parent])
        {
            Swap(a + bigchild, a + parent);
            parent = bigchild;
            bigchild = parent * 2 + 1;
        }
        else
            break;
    }
}
void HeapSort(SortDataType* a, int num)
{
    assert(a&&num);
    //向下建堆
    for (int parent = (num - 1) / 2; parent >= 0; parent--)
    {
        AdjustDown(a, parent, num);
    }
    //调整,最大的调整至数组末尾,数组堆空间减1
    while(num!=0)
    {
        Swap(a, a + num - 1);
        AdjustDown(a, 0, --num);
    }
}

main.c

#include"heapsort.h"
int main()
{
    int arry[1];
    for (int i = 0; i < 10; i++)
    {
        arry[i] = 10 - i;
    }
    HeapSort(arry, 10);
    for (int i = 0; i < 10; i++)
    {
        printf("%d ", arry[i]);
    }
    printf("\n");
    return 0;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值