加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】计数排序

发布时间:2020-12-15 05:59:38 所属栏目:安全 来源:网络整理
导读:对于一个int数组,请编写一个计数排序算法,对数组元素排序。 给定一个int数组A及数组的大小n,请返回排序后的数组。 测试样例: [1,2,3,5,3],6 [1,5] #includeiostream #includestring using namespace std ; class CountingSort { public : void display(

对于一个int数组,请编写一个计数排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,3],6
[1,5]

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


class CountingSort {
public:

    void display(int * A,int n){
        for (int i = 0; i < n; i++){
            printf("%d ",A[i]);
        }
        printf("n");
    }
    void swap(int * A,int * B){
        int temp = *A;
        *A = *B;
        *B = temp;
    }


    int* countingSort(int* A,int n) {
        // write code here

        int min_val,max_val;
        min_val = max_val = A[0];
        for (int i = 0; i < n; i++){
            if (A[i] < min_val)
                min_val = A[i];
            if (A[i] > max_val)
                max_val = A[i];
        }

        int n1 = max_val - min_val + 1;
        int * a = new int[n1]();

        for (int i = 0; i < n; i++){
            a[A[i] - min_val]++;
        }

        int counter = 0;
        for (int i = 0; i < n1; i++){
            for (int j = 0; j < a[i]; j++){
                A[counter++] = i + min_val;
            }
        }

        delete[] a;

        return A;
    }
};


int main()
{
    CountingSort s;
    int A[] = { 54,35,48,36,27,12,44,8,14,26,17,28 };
    int n = 13;
    s.countingSort(A,n);
    s.display(A,n);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读