Counting Sort 2

Sort by

recency

|

388 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

    My Python3 solution:

    def countingSort(arr: list[int]) -> list[int]:
        # Write your code here
        freq = [0] * 100
        for num in arr:
            freq[num] += 1
    
        x: list[int] = [i for i in range(100) for _ in range(freq[i])]
    
  • + 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;
    }