Counting Sort 2

Sort by

recency

|

395 Discussions

|

  • + 0 comments

    NodeJS

    function countingSort(arr) {
        let count = new Array(100).fill(0);
        let result=[];
        
        for(let i=0;i<arr.length;i++) count[arr[i]]++;
        for(let i=0;i<100;i++) {
            while(count[i]>0){
                result.push(i)
                count[i]--;
            }
        }
        return result
        
    }
    
  • + 0 comments

    Here is problem solution in python java c++ c and Javascript - https://programmingoneonone.com/hackerrank-counting-sort-2-problem-solution.html

  • + 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 Java solution with o(n) time complexity and o(n) space complexity:

    public static List<Integer> countingSort(List<Integer> arr) {
            int[] freqArr = new int[100];
            arr.forEach(num -> freqArr[num]++);
    
            return IntStream.range(0, 100)
                .boxed()
                .flatMap(i -> Collections.nCopies(freqArr[i], i).stream())
                .collect(Collectors.toList());
        }
    
  • + 0 comments
    1. Time Complexity: O(n)
    2. Space Complexity: O(n)
    int* countingSort(int arr_count, int* arr, int* result_count) {
        static int res_map[100] = {0};
        *result_count = 0;
        for (int i = 0; i<arr_count; i++){
            res_map[arr[i]] ++;
        }
        for (int i = 0; i<100; i++){
            if (res_map[i] != 0){
                for (int j = 0; j<res_map[i]; j++){
                    arr[(*result_count)] = i;
                    (*result_count)++;
                }
            }
        }
        return arr;
    }