堆排序排序c语言_C中堆排序程序

本文提供了一个简单的C语言程序,用于实现堆排序算法。堆排序是一种基于比较的排序技术,利用二进制堆数据结构。程序包括用户输入元素,排序过程,最后输出排序后的数组。
摘要由CSDN通过智能技术生成

堆排序排序c语言

Here you will get program for heap sort in C.

在这里,您将获得用于在C中进行堆排序的程序。

It is a comparison based sorting technique which uses binary heap data structure.

这是一种基于比较的排序技术,它使用二进制堆数据结构。

Below I have shared simple program to implement this sorting technique in C.

下面,我共享了一个简单的程序来在C中实现此排序技术。

C中堆排序程序 (Program for Heap Sort in C)

#include<stdio.h>
 
void create(int []);
void down_adjust(int [],int);
 
void main()
{
	int heap[30],n,i,last,temp;
	printf("Enter no. of elements:");
	scanf("%d",&n);
	printf("\nEnter elements:");
	for(i=1;i<=n;i++)
		scanf("%d",&heap[i]);
	
	//create a heap
	heap[0]=n;
	create(heap);
	
	//sorting
	while(heap[0] > 1)
	{
		//swap heap[1] and heap[last]
		last=heap[0];
		temp=heap[1];
		heap[1]=heap[last];
		heap[last]=temp;
		heap[0]--;
		down_adjust(heap,1);
	}
 
	//print sorted data
	printf("\nArray after sorting:\n");
	for(i=1;i<=n;i++)
		printf("%d ",heap[i]);
}
 
void create(int heap[])
{
	int i,n;
	n=heap[0]; //no. of elements
	for(i=n/2;i>=1;i--)
		down_adjust(heap,i);
}
 
void down_adjust(int heap[],int i)
{
	int j,temp,n,flag=1;
	n=heap[0];
	
	while(2*i<=n && flag==1)
	{
		j=2*i;	//j points to left child
		if(j+1<=n && heap[j+1] > heap[j])
			j=j+1;
		if(heap[i] > heap[j])
			flag=0;
		else
		{
			temp=heap[i];
			heap[i]=heap[j];
			heap[j]=temp;
			i=j;
		}
	}
}

Output

输出量

Enter no. of elements:5

输入编号 元素:5

Enter elements:12 8 46 23 7

输入元素:12 8 46 23 7

Array after sorting: 7 8 12 23 46

排序后的数组: 7 8 12 23 46

翻译自: https://www.thecrazyprogrammer.com/2013/12/c-program-for-sorting-array-using-heap-sort.html

堆排序排序c语言

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值