计数排序

计数排序是一种算法复杂度 O(n) 的排序方法,适合于小范围集合的排序。计数排序是一个类似于桶排序的排序算法,其优势是对已知数量范围的数组进行排序。它创建一个长度为这个数据范围的数组countArray,countArray中每个元素记录要排序数组中对应记录的出现个数。这个算法于1954年由 Harold H. Seward 提出。

计数排序非常基础,它的主要目的是对整数排序并且会比普通的排序算法性能更好。例如,输入{ 8, 17,3,5,6,2,6,15}给计数排序,会输出 {2,3,5,6,6,8,15,17}这个算法由以下步骤组成:

  1. 初始化一个计数数组,大小是输入数组中的最大的数减去最小数再加一。然后将其每个数都置零。
  2. 遍历输入数组,遇到一个数就在计数数组对应的位置上加一。
  3. 把计数数组直接覆盖到输出数组(节约空间)。

程序代码

 1 #include<iostream>
 2 
 3 #include<assert.h>
 4 
 5 using namespace std;
 6 
 7 void countSort(int *a,size_t size)
 8 
 9 {
10 
11   assert(a);
12 
13   int max=a[0];
14 
15   int min=a[0];
16 
17   for(size_t i=1;i<size;i++)
18 
19   {
20 
21     if(a[i]<min)
22 
23     {
24 
25         min=a[i];
26 
27     }
28 
29     else if(a[i]>max)
30 
31     {
32 
33         max=a[i];
34 
35     }
36 
37     int range=max-min+1;
38 
39     int *countArray=new int[range];
40 
41     memset(countArray,0,sizeof(int)*range);
42 
43     for(size_t i=0;i<size;i++)
44 
45     {
46 
47       countArray[a[i]-min]++;
48 
49     }
50 
51     sizt_t  index=0;
52 
53     for(size_t i=0;i<range;i++)
54 
55     {
56 
57       while(countArray[i]-->0)
58 
59       {
60 
61         a[index++]=i+min;
62 
63           }
64 
65     }
66 
67 }   
68 
69 void PrintArray(int *a, size_t size)
70 {
71    assert(a);
72    for (size_t i = 0; i<size; i++)
73    {
74       cout<<a[i]<<" ";
75    }
76    cout << endl;   
77 }
78 void  main()
79 {
80      int  br[] = { 20, 80, 90, 589, 998, 965, 852, 123, 456, 789 };
81    int len = sizeof(br) / sizeof(int);
82    cout << "原数据如下:" << endl;
83    PrintArray(br, len);
84    cout << "排序后数据如下:" << endl;
85    countSort(br, len);
86    PrintArray(br, len);
87    system("pause");
88 } 

 

posted @ 2016-04-10 11:08  *尘封的记忆*  阅读(204)  评论(0编辑  收藏  举报