计数排序算法

1.        The precondition and The scope of application

Counting sort assumes that each of the n inputelements is an integer in the range[0,k], for some integer k.

2.        Algorithm thought

Counting sort determines, for each inputelement x, the number of elements less than x. It uses this information toplace element x directly into its position in the output array. For example, if17 elements are less than x, then x belongs in output position 18. We must modify this scheme slightly to handle the situation in which severalelements have the same value.

3.        Implementation and Annotation

/*
Variables illustrations:
unsortedarray:
The array that stores arraysizeunsorted integers which are all in the range [0,maxnum];
sortedarray:
The result array that storessorted integers which are all come from unsortedarray ;
occurrence:
occurrence[certainnumber] means that thenumber of integers which are equal or lesser than certainnumber inunsortedarray;
arraysize:
The number of unsorted integersvidelicet the number of elements in unsortedarray;
maxnum:
A certain number satisfy that allintegers in unsortedarray are equal or lesser than it.
*/
 
void CountingSort(int *unsortedarray, int*sortedarray, int *occurrence, int arraysize,int maxnum)
{
   //Initialize the occurrence array: Assign 0 to every element inoccurrence.
   for(int index=0;index<=maxnum; index++)
   {
        occurrence[index]=0;
   }
 
   //First we count the frequency of every integer in unsortedarrray.
   for(int index=0;index<arraysize; index++)
   {
        occurrence[unsortedarray[index]]++;
   }
 
   //Second we compute for each i=0;1; …… ;k how manyinput elements are less than
   //or equal to i by keeping arunning sum of the array occurrence
   for(int index=1;index<=maxnum;index++)
   {
        occurrence[index]=occurrence[index]+occurrence[index-1];
   }
 
   //Place each element inunsortedarray into its correct sorted position
   //in the array sortedarray.
   for(intindex=arraysize-1;index>=0;index--)
   {
        sortedarray[occurrence[unsortedarray[index]]-1]=unsortedarray[index];
        occurrence[unsortedarray[index]]--;
   }
 
   ///Output the sorted array ;
   cout<<"The array after sorting is :\n";
   for(int index=0;index<arraysize;index++)
   {
       cout<<sortedarray[index]<<" ";
   }
   cout<<endl;
}

4.        Key components’ illustrations

1)        Counting sort is stable:numbers with the samevalue appear in the output array in the same order as they do in the inputarray. This property is implemented by the following code.

for(int index=arraysize-1;index>=0;index--)
{
  sortedarray[occurrence[unsortedarray[index]]-1]=unsortedarray[index];occurrence[unsortedarray[index]]--;
}

There are occurrence[unsortedarray[index]] elementsless than or equal to unsortedarray[index].The subscript in sortedarray is alsostart from 0, so occurrence[unsortedarray[index]]-1 is the right subscript for unsortedarray[index]in the array sortedarray. We decrease occurrence[unsortedarray[index]] each timewe place a value unsortedarray[index] into the sortedarray array. We traversethe unsortedarray array from back to front and if several elements have thesame value, the subscript for the same value is decreasing, so the subscript ofthe last element that equal to value is the largest among all the subscripts ofelements that is equal to value. So counting sort is stable.

5.        Complexity analysis(n is the number of integers; k is the high bound)

1)        Time complexity

The initialization of theoccurrence array, and the second for loop which performs a prefix sum on the occurrencearray, each iterate at most k +1 times and therefore take O(k) time. The other two for loopseach take O(n) time. Therefore the time forthe whole algorithm is the sum of the times for these steps, O(n + k).In practice, we usually use counting sort when we have k=O(n), in which casethe running time isΘ(n). Any comparison sort algorithm requires Ω(nlg n) comparisons in theworst case, and counting sort is not a comparison sort.

2)        Space complexity

Because it uses arrays oflength k +1 and n, the totalspace usage of the algorithm is also O(n + k). For problem instances in whichthe maximum key value is significantly smaller than the number of items,counting sort can be highly space-efficient, as the only storage it uses otherthan its input and output arrays is the Count array which uses space O(k).

6.        Test program

#include<iostream>
using namespace std;
 
void CountingSort(int *unsortedarray, int*sortedarray, int *occurrence, int arraysize,int maxnum);
 
int main()
{
   int unsortedarray[100],sortedarray[100],occurrence[110];
   int maxnum=100, arraysize;
   int test=10;
   cout<<"You can test the program for ten times.\n";
   while(test--)
   {
        cout<<"Please input the sizeof array that is unsorted.\n";
        cin>>arraysize;
        cout<<"Please input"<<arraysize<<" integers that in the range[0,100].\n";
        for(int index=0; index<arraysize;index++)
        {
            cin>>unsortedarray[index];
        }
 
       CountingSort(unsortedarray,sortedarray,occurrence,arraysize,maxnum);
 
   }
   return 0;
}
 
void CountingSort(int *unsortedarray, int*sortedarray, int *occurrence, int arraysize,int maxnum)
{
   for(int index=0; index<=maxnum; index++)
   {
        occurrence[index]=0;
   }
 
   for(int index=0; index<arraysize; index++)
   {
        occurrence[unsortedarray[index]]++;
   }
 
   for(int index=1; index<=maxnum; index++)
   {
        occurrence[index]=occurrence[index]+occurrence[index-1];
   }
 
   for(int index=arraysize-1; index>=0; index--)
   {
       sortedarray[occurrence[unsortedarray[index]]-1]=unsortedarray[index];
        occurrence[unsortedarray[index]]--;
}
 
   cout<<"The array after sorting is :\n";
   for(int index=0; index<arraysize; index++)
   {
       cout<<sortedarray[index]<<" ";
   }
   cout<<endl;
}

7.        Optimize and Improve

There is one version thatcan lower running time and save space, but is not stable anymore. Following arethe code.

void CountingSort(int*unsortedarray, int *occurrence, int arraysize, int maxnum)
{
   for(int index=0; index<=maxnum; index++)
   {
        occurrence[index]=0;
   }
 
   for(int index=0; index<arraysize; index++)
   {
        occurrence[unsortedarray[index]]++;
}
 
   int cnt=0;
   cout<<"The array after sorting is \n";
   for(int index=0;index<=maxnum;index++)
   {
        while(occurrence[index]--)
        {
            cout<<index<<"";
            unsortedarray[cnt++]=index;
        }
   }
   cout<<endl;
}

This version don’t need to compute the prefixsum of the occurrence array and don’t need the sortedarray. When the sortingdon’t have limitations about stability, this version is better.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值