数据结构-排序算法之堆排序(C语言实现)
#include<stdio.h>#include<malloc.h>#include<time.h>#define MAX 10void swap(int a[],int pos1, int pos2){int temp = a[pos1];a[pos1] = a[pos2];a[pos2] = temp;}void Heap_Adjust(int a[],
·
#include<stdio.h>
#include<malloc.h>
#include<time.h>
#define MAX 10
void swap(int a[],int pos1, int pos2)
{
int temp = a[pos1];
a[pos1] = a[pos2];
a[pos2] = temp;
}
void Heap_Adjust(int a[], int pos, int len)
{
int max = pos;
int lchild = 2*pos + 1;
int rchild = 2*pos + 2;
if (lchild < len && a[lchild] > a[max])
{
max = lchild;
}
if (rchild < len && a[rchild] > a[max])
{
max = rchild;
}
if (max != pos)
{
swap(a, max, pos);
Heap_Adjust(a, max, len);
}
}
void Heap_Sort(int a[], int length)
{
// 初始化堆
for (int i = length/2-1; i >= 0; i--)
{
Heap_Adjust(a, i, length);
}
// 交换堆顶与堆尾
for (int i = length-1; i >= 0; i--)
{
swap(a, 0, i);
Heap_Adjust(a, 0, i);
}
}
void Show(int a[])
{
for (int i = 0; i < MAX; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
// int a[] = {4,2,5,0,5,7,1,3,9};
int a[MAX];
srand((unsigned int)time(NULL));
for (int i = 0; i < MAX; i++)
{
a[i] = rand() % MAX;
}
Show(a);
Heap_Sort(a, MAX);
Show(a);
return 0;
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)