zoukankan      html  css  js  c++  java
  • 计数排序算法(C语言实现)

    计数排序,  比较适合数值跨度比较小的,  也就是数组中最大值减去最小值得到的值尽量小,  同时数组元素又比较多的情况下用计数排序效率比较高,同时,计数排序算法基友稳定性。

    计数排序的时间复杂度为O(n),计数排序是用来排序0到100之间的数字的最好的算法。

    算法的步骤如下:

          1.找出待排序的数组中最大和最小的元素

          2.统计数组中每个值为i的元素出现的次数,存入数组C的第i项

          3.对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加)

          4.反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1

    下面直接贴个C语言实现的代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    void print_arry(int *arr,int n)
    {
    	int i;
    	for(i = 0; i<n; i++)
    	{
    		printf("%d ", arr[i]);
    	}
    	printf("\n");
    }
    void count_sort(int *arr, int *sorted_arr, int n)
    {
    	int *count_arr = (int *)malloc(sizeof(int) * 100);
    	int i; 
    	//初始化计数数组 
    	for(i = 0; i<100; i++)
    		count_arr[i] = 0;
    	//统计i的次数 
    	for(i = 0;i<n;i++)
    		count_arr[arr[i]]++;
    	//对所有的计数累加 
    	for(i = 1; i<100; i++)
    		count_arr[i] += count_arr[i-1]; 
    	//逆向遍历源数组(保证稳定性),根据计数数组中对应的值填充到先的数组中 
    	for(i = n; i>0; i--)
    	{
    		sorted_arr[count_arr[arr[i-1]]-1] = arr[i-1];
    		count_arr[arr[i-1]]--;	
    	} 
    	free(count_arr);
    }
    int main() {
    	int n,i;
    	printf ("待排序数组的大小 n="); 
    	scanf ("%d", &n); 
    	
    	int *arr = (int *)malloc(sizeof(int) * n);
    	int *sorted_arr = (int *)malloc(sizeof(int) * n);
    	
    	srand (time (0));
    	for (i = 0; i<n; i++)
    	{
    		arr[i] = rand() % 100;
    	}
    	printf ("随机生成数值为0~99的数组...\n");
    	printf ("初始化数组: ");
    	print_arry(arr, n);
    	count_sort(arr, sorted_arr, n);
    	printf ("排序后的数组:"); 
    	print_arry(sorted_arr, n);
    	return 0;
    	system ("pause");
    	
    }


     

  • 相关阅读:
    G1垃圾回收器的参数配置(JDK9的默认垃圾回收器)
    top.layer.open父子调用
    前端非空方法
    JS接收后台拼接好的标签 Uncaught SyntaxError: Invalid or unexpected token
    oracle 历史记录查询sql
    【python】使用pyinstaller将python程序打包成可执行的exe
    【python】使用pyinstaller打包exe闪退,cmd查看exe报错原因
    【python】turtle绘图几个超好看的颜色
    【python】trutle绘制送给女神的玫瑰花图
    【python】turtle龟绘制无敌螺旋转
  • 原文地址:https://www.cnblogs.com/MockingBirdHome/p/3040871.html
Copyright © 2011-2022 走看看