计数排序

第一个函数直接在原数组上排序

第二个函数不改动原有的数组,会生成新数组并返回

void countSort(int* a, int len) {
    if (a == nullptr || !len)return;
    int min = a[0], max = a[0];
    for (int i = 1; i < len; i++) {
        if (a[i] > max)max = a[i];
        else if (a[i] < min)min = a[i];
    }
    int* cnt = new int[max - min + 1]{0};
    for (int i = 0; i < len; i++) cnt[a[i] - min]++;

    for (int i = 0, j = min; i < len && j <= max; j++) {
        for (int k = cnt[j - min]; k > 0; k--)a[i++] = j;
    }
    delete[] cnt;
}
int* countSort2(int* a, int len) {
    if (a == nullptr || !len)return nullptr;
    int min = a[0], max = a[0];
    for (int i = 1; i < len; i++) {
        if (a[i] > max)max = a[i];
        else if (a[i] < min)min = a[i];
    }
    int* cnt = new int[max - min + 1]{ 0 };
    for (int i = 0; i < len; i++) cnt[a[i] - min]++;

    for (int i = 0; i < max - min; i++)cnt[i + 1] += cnt[i];
    int* temp = new int[len];
    for (int i = len-1; i >= 0; i--) {
        temp[cnt[a[i] - min] - 1] = a[i];
        cnt[a[i] - min]--;
    }

    delete[] cnt;
    return temp;
}
void test02() {


    //sizeof(a) / sizeof(*a)
    int a3[] = { 49,38,65,97,76,13,27,49 };
    int a7[] = { 15,1,2,3,5,8,4,9,6,7 };
    int a2[] = { 1,2,3,4,5,7,8,9,10,6 };
    int a4[] = { 1,2,3,4,5,7,8,9,10,6 };
    int a6[] = { 8,3,6,4,2,1,5,7,9,10,12,11 };
    int a9[] = { 16,9,20,15,3,18,13,2,17,10,5,7,11,12,6,1,19,4,8,14 };
    int a8[] = { 53,17,78,9,45,65,87,32 };
    int a5[] = { 53, 3, 542, 748, 14, 214, 154, 63, 616 };
    int a10[] = { 20,30,40,50,70,31,19,60 };
    int a[] = { 1,3,7,14,8,5,11,17,13,6,12,20,23,26,4,19 };
    int b[] = { 1,3,7,14,8,5,11,17,13,6,12,20,23,26,4,19 };
    //qsort(a, sizeof(a) / sizeof(*a), sizeof(*a), [](const void* a, const void* b)->int {return *(int*)a - *(int*)b; });
    //my_printAry(a, sizeof(a) / sizeof(*a));

    int* temp=countSort2(b, sizeof(b) / sizeof(*b));
    my_printAry(temp, sizeof(b) / sizeof(*b));

    countSort(b, sizeof(b) / sizeof(*b));
    my_printAry(b, sizeof(b) / sizeof(*b));

    int cnt = 0;
    for (int i = 0; i < sizeof(b) / sizeof(*b); i++)if (b[i] != temp[i])cnt++;
    cout << cnt << endl;
    delete[] temp;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值