计数排序

#include <iostream>
#include<algorithm>
using namespace std;

class CountingSort {

    int* jishu(int* A, int n, int k){
        int* a = new int[k + 1];
        //A[6],a[21]
        for (int i = 0; i < k + 1; i++)
            a[i] = 0;
        for (int i = 0; i < n; i++)
            a[A[i]]++;//a的结构类似于[0][1]...[21];A[i]范围{16,7,3,20,17,8}
        int t = 0;
        for (int i = 0; i<k + 1; i++){
            while (a[i]>0){
                A[t++] = i;
                a[i]--;
            }
        }
        delete[] a;
        return A;
    }
public:
    int* countingSort(int* A, int n) {
        if (A == NULL || n < 0) return NULL;
        int max = A[0];
        for (int i = 1; i < n; i++){
            if (A[i] > max)
                max = A[i];
        }
        return jishu(A, n, max);
    }
};
int main(int argc, char *argv[])
{
    int a[]={16,7,3,20,17,8};
    int size;
    CountingSort* hs = new CountingSort();
    int* resu=hs->countingSort(a, 6);
    int i;
        for (i = 0; i < 6; i++)
            cout << resu[i] << " ";
        cout << endl;
        system("pause");
    return 0;
}

你可能感兴趣的:(C++,技术排序)