Often, when a list is sorted, the elements being sorted are just keys to other values. For example, if you are sorting files by their size, the sizes need to stay connected to their respective files. You cannot just take the size numbers and output them in order, you need to output all the required file information.

The counting sort is used if you just need to sort a list of integers.  Rather than using a comparison, you create an integer array whose index range covers the entire range of values in your array to sort.  Each time a value occurs in the original array, you increment the counter at that index.  At the end, run through your counting array, printing the value of each non-zero valued index that number of times.

For example, consider an array $arr=[1,1,3,2,1]$.  All of the values are in the range $[0\ldots3]$, so create an array of zeroes, $result=[0,0,0,0]$.  The results of each iteration follow:

i	arr[i]	result
0	1	[0, 1, 0, 0]
1	1	[0, 2, 0, 0]
2	3	[0, 2, 0, 1]
3	2	[0, 2, 1, 1]
4	1	[0, 3, 1, 1]

Now we can print the sorted array: $sorted=[1,1,1,2,3]$.

Challenge 

Given an unsorted list of integers, use the counting sort method to sort the list and then print the sorted list. 

Hint: You can use your previous code that counted the items to print out the actual values in order.  

Function Description  

Complete the countingSort function in the editor below.  It should return the original array, sorted ascending, as an array of integers.  

countingSort has the following parameter(s):  

arr: an array of integers  

Input Format

The first line contains an integer $n$, the length of $\textbf{arr}$.
The next line contains space-separated integers $arr\left[i\right]$ where $0\leq i<n$.

Constraints

$0\leq n\leq1000000$ 

$0\leq arr[i]<100$ 

Output Format

Print the sorted list as a single line of space-separated integers. 

Sample Input
100
63 25 73 1 98 73 56 84 86 57 16 83 8 25 81 56 9 53 98 67 99 12 83 89 80 91 39 86 76 85 74 39 25 90 59 10 94 32 44 3 89 30 27 79 46 96 27 32 18 21 92 69 81 40 40 34 68 78 24 87 42 69 23 41 78 22 6 90 99 89 50 30 20 1 43 3 70 95 33 46 44 9 69 48 33 60 65 16 82 67 61 32 21 79 75 75 13 87 70 33 

Sample Output

 1 1 3 3 6 8 9 9 10 12 13 16 16 18 20 21 21 22 23 24 25 25 25 27 27 30 30 32 32 32 33 33 33 34 39 39 40 40 41 42 43 44 44 46 46 48 50 53 56 56 57 59 60 61 63 65 67 67 68 69 69 69 70 70 73 73 74 75 75 76 78 78 79 79 80 81 81 82 83 83 84 85 86 86 87 87 89 89 89 90 90 91 92 94 95 96 98 98 99 99 

Explanation

Once our counting array has been filled, loop from index $\mbox{o}$ to the end, printing each $\boldsymbol{i}$ value $arr\left[i\right]$ times.

Difficulty: EASY

Solutions:
import random
n = int(input())
ar = [int(x) for x in input().split()]

def countsort(ar):
	counts = [0] * 100
	for x in ar:
		counts[x] += 1
	return counts
res = countsort(ar)

def inorder(array):
	lst = []
	for i in range(len(array)):
		for x in range(array[i]):
			lst.append(i)
	return lst
finals = inorder(res)
print(' '.join(map(str, finals)))


from collections import Counter
input()
cc = Counter([int(x) for x in input().split()])
sk = list(dict(cc).keys())
sk.sort()
for k in sk:
	for i in range(cc[k]):
		print(k, end=' ')


import sys

def counting(arr, s):
	appearences = {}
	for x in range(100):
		appearences[x] = 0
	for value in arr:
		appearences[value] += 1
	result = []
	for x in range(100):
		if appearences[x] != 0:
			for a in range(appearences[x]):
				result.append(x)
	return result
size = int(sys.stdin.readline().strip())
array = sys.stdin.readline().strip().split()
array = [int(i) for i in array]
print(' '.join([str(i) for i in counting(array, len(array))]))


counts = dict()
n = int(input())
ar = [int(x) for x in input().split()]
for num in ar:
	counts[num] = counts.get(num, 0) + 1
out = []
for i in range(100):
	for j in range(counts.get(i, 0)):
		out.append(str(i))
print(' '.join(out))


N = int(input())
print(' '.join([str(x) for x in sorted([int(x) for x in input().split()])]))


int(input())
allInput = input()
allInput = [int(n) for n in allInput.split()]
allInput.sort()
s = ''
for i in allInput:
	s += str(i) + ' '
print(s)


N = int(input())
input_map = list(map(int, input().split()))
counter = [0] * 100
for element in input_map:
	counter[element] += 1
output = ''
i = 0
while i < 100:
	key = counter[i]
	for j in range(key):
		output = output + str(i) + ' '
	i = i + 1
print(output)


counter = [int(0) for i in range(100)]
N = int(input())
ar = [int(x) for x in input().split()]
for v in ar:
	counter[v] += 1
print(''.join(' '.join((str(x) for x in range(len(counter)) for _ in range(counter[x])))))


from sys import stdin

def main():
	stdin.readline()
	numbers = list(map(int, stdin.readline().split()))
	frequencies = {}
	for i in numbers:
		if i in frequencies:
			frequencies[i] += 1
		else:
			frequencies[i] = 1
	for i in range(100):
		if i not in frequencies:
			frequencies[i] = 0
		for j in range(frequencies[i]):
			print(i, end=' ')
main()


count = input()
nums = list(map(int, input().split()))

def sort(arr):
	less = []
	equal = []
	greater = []
	if len(arr) > 1:
		pivot = arr[0]
		for i in range(len(arr)):
			if arr[i] > pivot:
				greater.append(arr[i])
			elif arr[i] < pivot:
				less.append(arr[i])
			else:
				equal.append(arr[i])
		return sort(less) + equal + sort(greater)
	else:
		return arr
s = sort(nums)
for i in range(len(s)):
	print(s[i], end=' ')


counters = [0 for x in range(100)]
n = int(input())
inp = input().split(' ')
for i in range(n):
	index = int(inp[i])
	counters[index] = counters[index] + 1
sorted = []
for i in range(100):
	count = counters[i]
	for j in range(count):
		sorted.append(i)
print(' '.join((str(x) for x in sorted)))


n = int(input())
c = [0 for i in range(100)]
l = 0
a = []
while l < n:
	a += input().split()
	l = len(a)
for i in a:
	c[int(i)] += 1
ans = ''
for j in range(len(c)):
	ans += c[j] * (str(j) + ' ')
print(ans)


def counting_sort(a):
	count = [0] * 100
	for x in a:
		count[x] += 1
	a.clear()
	for i in range(len(count)):
		a += [i] * count[i]
	return a
n = int(input())
a = [int(x) for x in str(input()).split()]
counting_sort(a)
print(' '.join([str(x) for x in a]))


input()
nums = [int(x) for x in input().split()]
count = [0] * 100
for i in nums:
	count[i] += 1
for i in range(len(count)):
	for j in range(count[i]):
		print(i, end=' ')


k = 100
n = int(input())
data = list(map(int, input().split()))
count = [0 for _ in range(k)]
output = [0 for _ in range(n)]
for x in data:
	count[x] += 1
total = 0
for i in range(k):
	old_count = count[i]
	count[i] = total
	total += old_count
for x in data:
	output[count[x]] = x
	count[x] += 1
print(' '.join(map(str, output)))


l = int(input())
a = list(input())
b = []
for x in range(0, l):
	b.append('')
index = 0
for x in range(0, len(a)):
	if a[x] != ' ':
		b[index] += a[x]
	if a[x] == ' ':
		index += 1
for x in range(0, len(b)):
	b[x] = int(b[x])
ans = [0] * 100
for x in range(l):
	ans[b[x]] += 1
ansx = []
for x in range(100):
	for y in range(ans[x]):
		ansx.append(x)
print(' '.join(map(str, ansx)))


n = int(input())
ar = list(map(int, input().split()))
c = [0] * 100
for e in ar:
	c[e] += 1
for i in range(len(c)):
	if c[i] > 0:
		print(' '.join([str(i)] * c[i]), end=' ')


from collections import defaultdict
n = int(input())
nbs = [int(i) for i in input().split()]
freq = defaultdict(lambda : 0)
for nb in nbs:
	freq[nb] += 1
ret = []
for i in range(max(nbs) + 1):
	for _ in range(freq[i]):
		ret.append(str(i))
print(' '.join(ret))


nombreEntrees = int(input())
ar = [int(i) for i in input().strip().split()]
tableauCompte = [0] * 100
for el in ar:
	tableauCompte[el] += 1
reponse = ''
for i in range(len(tableauCompte)):
	if tableauCompte[i] != 0:
		reponse += (str(i) + ' ') * tableauCompte[i]
print(reponse.rstrip())


size = int(input().strip())
counts = {}
for i in range(100):
	counts[i] = 0
for number in input().strip().split():
	num = int(number)
	counts[num] = counts[num] + 1
countsArr = []
for i in range(100):
	for j in range(counts[i]):
		countsArr.append(str(i))
print(' '.join(countsArr))


N = int(input())
ar = [int(i) for i in input().split()]
res = [0] * 100
for val in ar:
	res[val] += 1
print(' '.join([' '.join([str(i)] * val) for (i, val) in enumerate(res) if val > 0]))


(n, ar) = (int(input()), map(int, input().split()))
counts = [''] * 100
for x in ar:
	counts[x] += str(x) + ' '
print(''.join(counts))


def counting_sort(array):
	res_array = [0 for i in range(100)]
	for a in array:
		res_array[a] += 1
	for i in range(len(res_array)):
		for j in range(res_array[i]):
			print(i, '', end='')
N = int(input())
array = [int(i) for i in input().strip().split()]
counting_sort(array)


N = int(input())
ar = list(map(int, input().split()))
ar.sort()
for num in ar:
	print(num, end=' ')


def count(lst):
	out = [0 for _ in range(100)]
	for el in lst:
		out[el] += 1
	return out

def out(lst):
	sorted_lst = []
	for (i, c) in enumerate(lst):
		if c != 0:
			sorted_lst.extend((i for _ in range(c)))
	return sorted_lst
n = int(input())
strlst = input()
cc = count([int(el) for el in strlst.split()])
result = out(cc)
print(' '.join((str(c) for c in result)))


n = int(input().strip())
ar = [int(i) for i in input().strip().split(' ')]
freq = [0 for i in range(100)]
for i in ar:
	freq[i] += 1
s = ''
for i in range(100):
	for j in range(freq[i]):
		s = s + str(i) + ' '
print(s)


input()
print(' '.join([str(i) for i in sorted([int(j) for j in input().split()])]))


t = int(input())
l = []
l.append(input())
res = []
res = l[0].split()
for x in range(t):
	res[x] = int(res[x])
res.sort()
for x in range(t):
	print(res[x], end=' ')


n = int(input())
m = 100
A = [int(s) for s in input().split()]
B = [0] * m
for i in range(n):
	B[A[i]] += 1
C = []
for i in range(m):
	C += [i] * B[i]
print(' '.join(map(str, C)))


input()
a = map(int, input().split())
print(*sorted(a))


DEV = False
if DEV:
	f = open('test_data.txt', 'r')
	ra_len = int(f.readline().strip())
	ra = [int(i) for i in f.readline().strip().split()]
else:
	ra_len = int(input().strip())
	ra = [int(i) for i in input().strip().split()]
counts = []
for num in range(0, 100, 1):
	counts.append(0)
for num in ra:
	counts[num] += 1
result = ''
for num in range(0, 100, 1):
	for repeats in range(0, counts[num]):
		result += '{0} '.format(num)
print(result)
if DEV:
	f.close()


input()
X = [0] * 100
for i in map(int, input().split()):
	X[i] += 1
for i in range(100):
	for j in range(X[i]):
		print(i, end=' ')


n = int(input())
ar = [int(number) for number in input().split()]
count = [0] * 100
for number in ar:
	count[number] += 1
for (i, j) in enumerate(count):
	for _ in range(j):
		print(i, end=' ')


cnt = [0 for i in range(101)]
n = int(input())
l = map(int, input().split())
for i in l:
	cnt[i] += 1
for i in range(100):
	for j in range(cnt[i]):
		print(i, end=' ')


size = int(input())
tmp = input()
li = tmp.split()
for i in range(0, size):
	li[i] = int(li[i])
li.sort()
for i in range(0, size):
	li[i] = str(li[i])
print(' '.join(li))


n = int(input())
arr = [int(x) for x in input().split()]

def countingSort(A, k):
	B = [-1 for x in range(len(A))]
	C = [0 for x in range(k)]
	for i in range(len(A)):
		C[A[i]] += 1
	for i in range(1, k):
		C[i] += C[i - 1]
	for i in range(len(A) - 1, -1, -1):
		B[C[A[i]] - 1] = A[i]
		C[A[i]] -= 1
	return B
sortedArr = countingSort(arr, 100)
print(' '.join(map(str, sortedArr)))


n = int(input())
ar = [int(i) for i in str(input()).split()]
count = [0] * 100
for i in ar:
	count[i] += 1
result = []
for (j, k) in enumerate(count):
	result += [str(j)] * k
print(' '.join(result))


from collections import defaultdict
arraySize = input()
array = [int(x) for x in input().split()]
occurrences = defaultdict(lambda : 0)
for element in array:
	occurrences[element] += 1
for x in range(100):
	if occurrences[x] != 0:
		print((str(x) + ' ') * occurrences[x], end='')


N = int(input().strip())
ar = [int(x) for x in input().strip().split()]
count = [0] * 100
for element in ar:
	count[element] += 1
sort = []
for i in range(len(count)):
	for j in range(count[i]):
		sort.append(i)
print(' '.join([str(x) for x in sort]))


n = input()
numbers = list(map(int, input().split()))
n_sorted = sorted(numbers)
print(' '.join(map(str, n_sorted)))


n = int(input())
numbers = [int(i) for i in input().split()]
arr = [0 for i in range(100)]
output = [0 for i in range(len(numbers))]
for i in range(n):
	arr[numbers[i]] += 1
for j in range(1, 100):
	arr[j] += arr[j - 1]
for k in range(n - 1, -1, -1):
	output[arr[numbers[k]] - 1] = numbers[k]
	arr[numbers[k]] -= 1
print(' '.join([str(i) for i in output]))