算法笔记 --- Counting Sort

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

class CountingSort {
public:
    int* countingSort(int* A, int n) {
        // write code here
        int* counting = new int[1000];
        int* tmp = new int[n];
        for(int i = 0; i < n; i++){
            tmp[i] = A[i];
        }
        fill(counting, counting+1000, 0);
        for(int i = 0; i < n; i++){
            counting[A[i]]++;
        }
 
        for(int i = 1; i < 1000; i++){
            counting[i] += counting[i-1];
        }
               cout<<"counting:"<<endl;
        for(int i = 0; i < n; i++){
            cout<<counting[i]<<" ";
        }
        cout<<endl;
        for(int j = n-1; j >= 0; j--){
            A[counting[tmp[j]]-1] = tmp[j];
            counting[tmp[j]]--;
        }
        
        delete [] tmp;
        delete [] counting;
        return A;
    }
};
int main()
{
    int a[13] = {54,35,48,36,27,12,44,44,8,14,26,17,28};
    int* res;
    CountingSort sorter;
    res = sorter.countingSort(a, 13);
    cout<<"after sorting:"<<endl;
    for(int i = 0; i < 13; i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
   
    return 0;
}

 

posted @ 2016-08-20 19:31  zhongzhiqiangZz  阅读(104)  评论(0编辑  收藏  举报