Counting Sort 2

Sort by

recency

|

380 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/TPW8IGrTI8A

    vector<int> countingSort(vector<int> arr) {
        vector<int> result, count(100, 0);
        for(int i = 0; i < arr.size(); i++) count[arr[i]]++;
        for(int i = 0; i < 100; i++) result.resize(result.size() + count[i], i);
        return result;
    }
    
  • + 0 comments

    Javascript:

    function countingSort(arr) {
       let maxNum = Math.max(...arr) + 1;
       let countArray = Array(maxNum).fill(0);
       let resultArray = Array();
       
       arr.forEach((num) => {
          countArray[num]++ 
       });
    
       countArray.forEach((result, index) => {
           for (var i = 0; i < result; i++) resultArray.push(index);
       });
       
       return resultArray;
    }
    
  • + 0 comments

    My Python3 solution:

    def countingSort(arr):
        idx_arr=(max(arr)+1)*[0]
        sorted_arr=[]
        
        for i in arr:
            idx_arr[i]+=1
        
        for i in range(len(idx_arr)):
            sorted_arr=sorted_arr + idx_arr[i]*[i]
        
        return sorted_arr
    
  • + 0 comments

    C++ (more at https://github.com/IhorVodko/Hackerrank_solutions/tree/master/Algorithms , feel free to give a star :) )

    std::vector<int> countingSort(std::vector<int> const & _nums) {
        using namespace std;
        vector<int> frequencies(100, 0);
        for(auto & num : _nums){
            ++frequencies.at(num);
        }
        vector<int> sorted;
        sorted.reserve(1'000'000);
        size_t count = 0;
        for(auto & frqnc : frequencies){
            while(frqnc--){
                sorted.emplace_back(count);
            }
            ++count;
        }
        sorted.shrink_to_fit();
        return sorted;
    }
    
  • + 0 comments

    python

    def countingSort(arr):
        res = []
        for i in range(max(arr) + 1):
            res += arr.count(i) * [i]
        return res