Skip to content

Commit 4a5919e

Browse files
authored
Merge pull request #894 from neha030/dev24
counting sort added
2 parents d537fd8 + 69b38e0 commit 4a5919e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Sorting Algorithms/counting_sort.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'''
2+
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+
def counting_sort(l, k=None):
21+
# creating an array for counting elements
22+
if k == None:
23+
arr = [0]*1000
24+
else:
25+
arr = [0]*(k+1)
26+
# counting the occurrence of elements
27+
for i in l:
28+
arr[i]+=1
29+
# generating sorted array
30+
l=[]
31+
for i in range(len(arr)):
32+
l+=[i]*arr[i]
33+
return l
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.
51+
'''

0 commit comments

Comments
 (0)