堆排序排序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语言