counting sort python

Solutions on MaxInterview for counting sort python by the best coders in the world

showing results for - "counting sort python"
Giorgio
14 Mar 2016
1# python program for counting sort
2
3def countingSort(arr):
4    size = len(arr)
5    output = [0] * size
6
7    # count array initialization
8    count = [0] * 10
9
10    # storing the count of each element 
11    for m in range(0, size):
12        count[arr[m]] += 1
13
14    # storing the cumulative count
15    for m in range(1, 10):
16        count[m] += count[m - 1]
17
18    # place the elements in output array after finding the index of each element of original array in count array
19    m = size - 1
20    while m >= 0:
21        output[count[arr[m]] - 1] = arr[m]
22        count[arr[m]] -= 1
23        m -= 1
24
25    for m in range(0, size):
26        arr[m] = output[m]
27
28data = [3,5,1,6,7,8,3]
29countingSort(data)
30print("Sorted Array: ")
31print(data)
32