![](https://i-blog.csdnimg.cn/blog_migrate/a416665f50c06aa3e3d3504f88fc3d73.png)
c4,3排序怎么计算
Counting sort algorithm is a sorting algorithm which do not involve comparison between elements of an array. In this tutorial I am sharing counting sort program in C. Steps that I am doing to sort the elements are given below.
计数排序算法是一种不涉及数组元素之间比较的排序算法。 在本教程中,我将共享C语言中的计数排序程序。下面是对元素进行排序的步骤。
1. First of all I am reading n elements in array a[]. While reading the array elements I have also calculated the maximum element.
1.首先,我正在读取数组a []中的n个元素。 在读取数组元素时,我还计算了最大元素。
2. Now the actual sorting is done in counting_sort() function. Here I am counting the occurrence of each element in the array a[] and then storing it at the index equal to the value of that element. For example occurrence of element 5 will be stored at index 5, occurrence of element 9 will be stored at index 9 and so on.
2.现在,实际排序是在count_sort()函数中完成的。 在这里,我计算数组a [] 中每个元素的出现,然后将其存储在等于该元素值的索引处。 例如,元素5的出现将存储在索引5中,元素9的出现将存储在索引9中,依此类推。
3. As the value at each index in count[] array is the occurrence of that index or element, so the elements are printed in ascending order by printing each index number of times equal to its corresponding value.
3.由于count []数组中每个索引处的值都是该索引或元素的出现,因此,通过打印等于其对应值的每个索引次数将元素以升序打印。
Also Read: Merge Sort in C
另请参阅: 合并C语言中的排序
![]() |
Counting Sort Example – Image Source |
计数排序示例– 图像源 |
I have also added a video tutorial below that will help you to understand the counting sort algorithm easily. If you are facing any problem then ask it in the comment section.
我还在下面添加了一个视频教程,可以帮助您轻松理解计数排序算法。 如果您遇到任何问题,请在评论部分提出。
用C进行计数的程序 (Program for Counting Sort in C)
#include<stdio.h>
void counting_sort(int a[],int n,int max)
{
int count[50]={0},i,j;
for(i=0;i<n;++i)
count[a[i]]=count[a[i]]+1;
printf("\nSorted elements are:");
for(i=0;i<=max;++i)
for(j=1;j<=count[i];++j)
printf("%d ",i);
}
int main()
{
int a[50],n,i,max=0;
printf("Enter number of elements:");
scanf("%d",&n);
printf("\nEnter elements:");
for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
if(a[i]>max)
max=a[i];
}
counting_sort(a,n,max);
return 0;
}
Output
输出量
![计数排序算法,C中的计数排序程序,计数排序示例 Counting Sort Algorithm, Counting Sort Program in C, Counting Sort Example](https://2.bp.blogspot.com/-gqa1Ldtvy4M/VR6h3qAZNiI/AAAAAAAAEPg/XcVA45URDHk/s1600/Counting%2BSort%2BProgram%2Bin%2BC.jpg)
翻译自: https://www.thecrazyprogrammer.com/2015/04/counting-sort-program-in-c.html
c4,3排序怎么计算