Ninja is studying sorting algorithms. He has studied all comparison-based sorting algorithms and now decided to learn sorting algorithms that do not require comparisons.
He was learning counting sort, but he is facing some problems. Can you help Ninja implement the counting sort?
For example:You are given ‘ARR’ = {-2, 1, 2, -1, 0}. The sorted array will be {-2, -1, 0, 1, 2}.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains an integer ‘N’ representing the length of the ‘ARR’ array.
The second line of each test case contains ‘N’ space-separated integers representing the ‘ARR’ array.
Output Format:
For each test case, print the sorted array.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= N <= 5000
-10^4 <= ARR[i] <= 10^4
Time limit: 1 sec
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
2
5
-2 1 2 -1 0
5
1 2 3 -4 -5
-2 -1 0 1 2
-5 -4 1 2 3
For the first test case, the sorted array will be {-2, -1, 0, 1, 2}.
For the second test case, the sorted array will be {-5, -4, 1, 2, 3}.
2
4
1 3 4 2
4
1 1 -1 -1
1 2 3 4
-1 -1 1 1
Try to map the frequency of every element to an index.
As the name suggests, counting sort is a sorting technique that counts the frequency of every unique element in the array, and this frequency is used in mapping to an index of a temporary array taken for sorting.
But since the input array also contains negative numbers, we can not map their frequency to an index. So, to overcome this problem, we will first find the minimum element, and instead of mapping the frequency of ‘ARR[I]’ to index ‘ARR[I]’, we will map the frequency to index ‘ARR[I]’ - 1.
Suppose ‘ARR’ = {-3, 1, 0 -1}.
MInimum element = -3.
After subtracting the minimum element from each element of ‘ARR’:
‘ARR’ = {0, 4, 3, 2}.
Now, we can easily map the frequency of every element to an index.
Algorithm:
O(N + K), where N is the length of the input array ‘ARR’ and K is the input range.
We are iterating through the input array thrice and the ‘COUNT’ array once. Hence the overall time complexity is O(N + k).
O(N + K). where N is the length of the input array ‘ARR’ and K is the input range.
The auxiliary arrays ‘ANS’ and ‘COUNT’ will have lengths ‘N’ and ‘K’, respectively. Hence the overall space complexity is O(N + K).