Counting Sort 2

Sort by

recency

|

387 Discussions

|

  • + 0 comments

    Python3

    def countingSort(arr):
        # Write your code here
        
        freq = [ arr.count(i) for i in range(max(arr))]
        
        x = [ num for num,count in enumerate(freq) for i in range(count)]
            
        return x
    
  • + 0 comments

    My answer in Typescript, just few changes

    function countingSort(arr: number[]): number[] {
        let arr_count = Array(100).fill(0)
    
        for (let i = 0; i < arr.length; i++) arr_count[arr[i]]++
    
        return arr_count.reduce((p, c, i) => [...p, ...Array(c).fill(i)], [])
    }
    
  • + 0 comments

    Java:

    public static List<Integer> countingSort(List<Integer> arr) {
      int[] freqArray = new int[100];
      List<Integer> sortedList = new ArrayList<>();
      for (int num : arr) {
        freqArray[num]++;
      }
    
      for (int i = 0; i < freqArray.length; i++) {
        for (int j = 0; j < freqArray[i]; j++) {
          sortedList.add(i);
        }
      }
    
      return sortedList;
    }
    
  • + 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
    def countingSort(arr):
        # Write your code here
        res=[0]*(max(arr)+1)
        s=[]
        for i in arr:
            res[i]+=1
        for i in range(len(res)):
            s.extend([i]*res[i])
        return s