Counting Sort

来源:互联网 发布:js数组冒泡排序 编辑:程序博客网 时间:2024/06/11 05:07

As for counting sort,we need to know the range of value of the array.It can not be too large. Than we count how many times the element comes. At last, we start from 0 to max value as i, if count[i] is non-zero, we append i to the new array until count[i] is zero. Finally, the array is sorted.

#include<bits/stdc++.h>using std::endl;using std::cout;int L[] = {2,3,8,7, 1, 2, 2, 2, 7, 3, 9, 8, 2, 1, 4, 2, 4, 6, 9, 2};int count[10];int _max = 10;void CountSort(int n){    int i;    for(i=0;i<n;i++){        count[L[i]]++;    }    int j = 0;    for(i=0;i<_max;i++){        while(count[i]){            L[j++] = i;            count[i]--;        }    }}int main(){    int n = sizeof(L)/4;    int i;    memset(count,0,sizeof(count));    CountSort(n);    for(i=0;i<n;i++){        cout<<L[i]<<' ';    }    cout<<endl;}
0 0
原创粉丝点击