You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Counting sort is a sorting algorithm that sorts the elements of an
3
+
array by counting the number of occurrences of each unique element in the array.
4
+
In this program default 'k' is 1000.
5
+
6
+
Algorithm
7
+
In Counting Sort, we will follow the following step-wise process:
8
+
9
+
First we will store the occurrence of elements in a count array.
10
+
11
+
Modify the count array such that every index store the sum of the previous count.
12
+
13
+
Traverse the given array from the end (so that stability maintains) and put the elements by checking our modified count array and the given input array.
14
+
15
+
And take a final array (output) and store the elements.
16
+
17
+
We get our sorted elements in the output array.
18
+
'''
19
+
20
+
defcounting_sort(l, k=None):
21
+
# creating an array for counting elements
22
+
ifk==None:
23
+
arr= [0]*1000
24
+
else:
25
+
arr= [0]*(k+1)
26
+
# counting the occurrence of elements
27
+
foriinl:
28
+
arr[i]+=1
29
+
# generating sorted array
30
+
l=[]
31
+
foriinrange(len(arr)):
32
+
l+=[i]*arr[i]
33
+
returnl
34
+
35
+
36
+
if__name__=="__main__":
37
+
l=list(map(int,input("Enter the elements of the list to be sorted:").split()))
38
+
l=counting_sort(l)
39
+
print("List after sorting:",*l)
40
+
41
+
'''
42
+
INPUT
43
+
Enter the elements of the list to be sorted:12 0 1 3 5 3 3 2 1 1
44
+
OUTPUT
45
+
List after sorting:0 1 1 1 2 3 3 3 5 12
46
+
47
+
Worst Case Complexity: O(n+k)
48
+
Best Case Complexity: O(n+k)
49
+
Average Case Complexity: O(n+k)
50
+
where n is size of an array , and k is element range of the array.
0 commit comments