算法笔记 --- Counting Sort

本文介绍了一种简单的计数排序算法实现方式,并提供了一个具体的示例程序。该程序使用 C++ 编写,通过计数排序对整数数组进行排序。
#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;
}

 

转载于:https://www.cnblogs.com/zhongzhiqiang/p/5791075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值