#include <bits/stdc++.h>
using namespace std;
// #Sorting #Theory
// https://www.geeksforgeeks.org/counting-sort/
int findMax(vector<int> a){
int max=INT_MIN;
for(int i=0;i<a.size();i++){
if(a[i]>max){
max=a[i];
}
}
return max;
}
/*
CountingSort is useful if we have multiple occurences of a same element in array
CountingSort only works with non-negative numbers as -ve index does not exit
Unstable - Order of elements is not preserved
example - array : 1 1 1 0 0 0 6 1 6 3 0 2 2
count :[0]4 [1]4 [2]2 [3]1 [4]0 [5]0 [6]2
[index i]value(number of times i occured in a)
*/
vector<int> CountingSort(vector<int> a){
int max=findMax(a); // find the largest number in a
vector<int> count(max+1); // make an array with max+1 size so we can have upto index 'max'
// count array stores the number of occurences of element a[i]
for(int i=0;i<a.size();i++){
count[a[i]]++; // number of a[i]'s in array += 1
}
for(int i=1;i<=max;i++){ //-------------IMP------ ( CLRS book: Pg 94)
count[i]+=count[i-1]; // this gives info of num of elements in array before a[i]
}
vector<int> sora(a.size()); // sorted a
for(int i=0;i<a.size();i++){
int x=count[a[i]]; // x is position where a[i] should be placed
sora[x-1]=a[i]; // nth postion has n-1 index
count[a[i]]--; // decrease count of a[i] by 1
}
return sora;
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<"Original: ";
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
vector<int> sora=CountingSort(a);
cout<<"Sorted: ";
for(int i=0;i<n;i++){
cout<<sora[i]<<" ";
}
cout<<endl;
}
return 0;
}