c_cpp 计数排序 - 不稳定

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 计数排序 - 不稳定相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>
using namespace std;

//  #Sorting #Theory

int findMax(vector<int> a){
    int max=INT_MIN;
    for(int i=0;i<a.size();i++){
        if(a[i]>max){
            max=a[i];
        }
    }
    return max;
}
/*
    CountingSort is useful if we have multiple occurences of a same element in array
    CountingSort only works with non-negative numbers as -ve index does not exit
    Unstable - Order of elements is not preserved
    example - array : 1 1 1 0 0 0 6 1 6 3 0 2 2
              count :[0]4 [1]4 [2]2 [3]1 [4]0 [5]0 [6]2
              [index i]value(number of times i occured in a)
*/
vector<int> CountingSort(vector<int> a){
    int max=findMax(a);   // find the largest number in a
    vector<int> count(max+1);  // make an array with max+1 size so we can have upto index 'max'
    // count array stores the number of occurences of element a[i]
    for(int i=0;i<a.size();i++){
        count[a[i]]++;  // number of a[i]'s in array += 1
    }
    return count;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        cout<<"Original: ";
        for(int i=0;i<n;i++){
            cout<<a[i]<<" ";
        }
        cout<<endl;
        vector<int> count=CountingSort(a);
        cout<<"Sorted: ";
        // we need to print the index i , count[i] times
        // i occurs count[i] times in the array
        int max=findMax(a);
        for(int i=0;i<=max;i++){	// printing from x=0 to x=max
            int x=count[i];
            while(x--){	// loop to print count[i] times
                cout<<i<<" ";
            }
        }
        cout<<endl;
    }
    
    return 0;
}

以上是关于c_cpp 计数排序 - 不稳定的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 计数排序

c_cpp 排序数组中的绝对不同计数

十大排序算法-快排-希尔-堆排-归并-冒泡-桶排-选择-插入-计数-基数-1

算法小结

计数排序与稳定排序

C++|计数排序[7]