Counting Sort 2

Sort by

recency

|

393 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 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;
    }
    
  • + 0 comments

    here is my Python solution

    def countingSort(arr):
        freq=[0]*100
        s_arr=[]
        for i in arr:
            freq[i]+=1
        
        for i in range(len(freq)):
            num=[i]*freq[i]
            s_arr.extend(num)
            
        return s_arr
    
  • + 0 comments

    Here is my Python solution!

    def counting(arr):
        frequency = [0 for i in range(100)]
        for num in arr:
            frequency[num] += 1
        return frequency
    
    def countingSort(arr):
        frequency = counting(arr)
        sortedarr = []
        for i in range(len(frequency)):
            for j in range(frequency[i]):
                sortedarr.append(str(i))
        return sortedarr