今天刚刚写完数据结构学习内部排序篇的学习日志,上网浏览一下网页又发现了几种自己完全没听过的排序算法。好吧好吧,我承认自己的确是菜鸟。 = =
计数排序
想写个计数排序,结果弄了一整天字符数组,呵呵,基础差没办法。
先介绍一下什么是计数排序吧:这是一个限制很大的算法,虽然效率可以达到O(n),但是应用范围不广。它的基本思想就是不通过比较来排序,而是通过直接统计元素在序列中应排位置的方法。他的算法是这样的:
首先,假设需要排序的元素的范围在0-k之内(多么大的一个限制啊)。然后创建一个计数数组,大小就是[0..k],数组中的每一位分别对应待排序序列的相应的数字,比如说待排序列中有一个32,那么count[32]对应的就是32在待排序列中出现的总次数(32有可能出现多次)。通过遍历一次待排序列,统计得到一个count数组,然后对这个数组作累加统计操作(有点类似于高数时候的积分),即for i=0 to k { count[i]=count[i-1]}, 这样就得到一个递增序列。而这个序列就是元素在排序后排序中所应该存放的位置。最后只需要根据这个递增序列,将待排序列中的元素输出到结果序列中就完成了。其中这种方法还是挺简单的,看看源代码好了:
- #include <stdio.h>
- #include <stdlib.h>
- const int LIST_LENGTH = 30;
- const int CHAR_LENGTH = 128;
- char *testcase[LIST_LENGTH] = {"jo","vicent","tom","honey","gigi","lily","susan","peter","bob","ron",
- "jason","henry","kiki","ken","auscar","vivian","yiyi","peace","iron","lotus",
- "andy","arta","ophone","denial","pipe","wade","james","kobe","kent","angel"};
- //Function Definition
- char** countSort(char **source);
- //Function Implementation
- char** countSort(char **source){
- //initialize the result pointer
- char **result = (char**)malloc(LIST_LENGTH*sizeof(char*));
- int count[CHAR_LENGTH]={0};
- int i;
- //generate the count array
- for (i=0;i<LIST_LENGTH;i++) count[**(source+i)]++;
- for (i=1;i<CHAR_LENGTH;i++) count[i] += count[i-1];
- int pos;
- for (i=0;i<LIST_LENGTH;i++) {
- pos = count[**(source+i)] -1 ;
- count[**(source+i)]--;
- *(result+pos) = *(source+i);
- }
- return result;
- }
- //test Function
- void testCountSort(){
- char** result;
- result = countSort(testcase);
- int i;
- for (i=0;i<LIST_LENGTH;i++) {
- printf(*(result+i));
- printf("/n");
- }
- }
- //Main Function
- void main(){
- testCountSort();
- }
to be con..