Counting Sort 2

  • + 1 comment

    This is the simplest algorithm I used, sharing 'cause I see a lot of twisted answers here in Discussions

    (C++)

    vector<int> countingSort(vector<int> arr) {
        vector<int> result(100,0);
        vector<int> sorted;
        for(int i=0;i<arr.size();i++)
            result[arr[i]]++;
        
        for(int i=0;i<result.size();i++)
            while(result[i]--)
                sorted.push_back(i);
        
        return sorted;
    }
    
    • [deleted]
      + 1 comment

      while(result[i]--) can you clarify please I didnt get it

      • + 2 comments

        In result vector, the frequency of the elements is stored, so suppose if "result[0] = 4" , this would mean there are 4 zeroes in our given array. Hence we would just push "0" 4 times in our sorted array (our final answer.) And to that - while(result[0]--) , this while loop will run until that 4 becomes 0, hence the "0" will get push_backed 4 times in "sorted" array.

        • [deleted]
          + 0 comments

          Thank you so much. I really appreciate your answer

        • + 0 comments

          Thanks, This helped me a lot.