还是算法:高级排序算法:计数,基数和桶排序

来源:互联网 发布:dlp数据防泄漏 编辑:程序博客网 时间:2024/04/29 05:39

今天刚刚写完数据结构学习内部排序篇的学习日志,上网浏览一下网页又发现了几种自己完全没听过的排序算法。好吧好吧,我承认自己的确是菜鸟。 = =

计数排序

想写个计数排序,结果弄了一整天字符数组,呵呵,基础差没办法。

先介绍一下什么是计数排序吧:这是一个限制很大的算法,虽然效率可以达到O(n),但是应用范围不广。它的基本思想就是不通过比较来排序,而是通过直接统计元素在序列中应排位置的方法。他的算法是这样的:

首先,假设需要排序的元素的范围在0-k之内(多么大的一个限制啊)。然后创建一个计数数组,大小就是[0..k],数组中的每一位分别对应待排序序列的相应的数字,比如说待排序列中有一个32,那么count[32]对应的就是32在待排序列中出现的总次数(32有可能出现多次)。通过遍历一次待排序列,统计得到一个count数组,然后对这个数组作累加统计操作(有点类似于高数时候的积分),即for i=0 to k { count[i]=count[i-1]}, 这样就得到一个递增序列。而这个序列就是元素在排序后排序中所应该存放的位置。最后只需要根据这个递增序列,将待排序列中的元素输出到结果序列中就完成了。其中这种方法还是挺简单的,看看源代码好了:

Code:
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4.   
  5. const int LIST_LENGTH = 30;  
  6. const int CHAR_LENGTH = 128;  
  7.   
  8. char *testcase[LIST_LENGTH] = {"jo","vicent","tom","honey","gigi","lily","susan","peter","bob","ron",  
  9.                             "jason","henry","kiki","ken","auscar","vivian","yiyi","peace","iron","lotus",  
  10.                             "andy","arta","ophone","denial","pipe","wade","james","kobe","kent","angel"};  
  11.   
  12.   
  13. //Function Definition  
  14. char** countSort(char **source);  
  15.   
  16. //Function Implementation  
  17. char** countSort(char **source){  
  18.     //initialize the result pointer  
  19.     char **result = (char**)malloc(LIST_LENGTH*sizeof(char*));  
  20.       
  21.     int count[CHAR_LENGTH]={0};  
  22.     int i;  
  23.       
  24.     //generate the count array  
  25.     for (i=0;i<LIST_LENGTH;i++) count[**(source+i)]++;  
  26.   
  27.     for (i=1;i<CHAR_LENGTH;i++) count[i] += count[i-1];  
  28.       
  29.     int pos;  
  30.     for (i=0;i<LIST_LENGTH;i++) {  
  31.         pos = count[**(source+i)] -1 ;  
  32.         count[**(source+i)]--;  
  33.         *(result+pos) = *(source+i);  
  34.     }  
  35.   
  36.     return result;  
  37. }  
  38. //test Function  
  39.   
  40. void testCountSort(){  
  41.     char** result;  
  42.     result = countSort(testcase);  
  43.   
  44.     int i;  
  45.     for (i=0;i<LIST_LENGTH;i++) {  
  46.         printf(*(result+i));  
  47.         printf("/n");  
  48.     }  
  49. }  
  50.   
  51.   
  52. //Main Function  
  53. void main(){  
  54.     testCountSort();  
  55.       
  56.   
  57. }     

to be con..