Skip to content

Commit f0aadb5

Browse files
committed
counting sort.py
1 parent e04ccb7 commit f0aadb5

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Python implementation for Counting Sort Algorithm
2+
3+
def countingsort(array):
4+
size = len(array)
5+
output = [0] * size
6+
7+
# Initialize the count array
8+
count = [0] * 10
9+
10+
# Store the count of each element in the count array
11+
for i in range(0, size):
12+
count[array[i]] += 1
13+
14+
# Store the cummulative count
15+
for i in range(1, 10):
16+
count[i] += count[i - 1]
17+
18+
# Find the index of each element of the original array in count array place the elements in output array
19+
i = size - 1
20+
while i >= 0:
21+
output[count[array[i]] - 1] = array[i]
22+
count[array[i]] -= 1
23+
i -= 1
24+
25+
# Copy the sorted elements into original array
26+
for i in range(0, size):
27+
array[i] = output[i]
28+
29+
30+
data = [4, 2, 2, 8, 3, 3, 1]
31+
countingsort(data)
32+
print("Sorted Array in Ascending Order: ")
33+
print(data)

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,7 @@
515515

516516
![](https://github.com/aish21/Algorithms-and-Data-Structures/blob/main/Resources/Animations/quicksort.gif)
517517

518-
### [Counting Sort](/Practice%20Concepts/Sorting/quick-sort.py)
518+
### [Counting Sort](/Practice%20Concepts/Sorting/counting-sort.py)
519519
* Sorts the elements of an array by counting the number of occurances of each unique element in the array.
520520
* The count is stored in an auxiliary array and the sorting is done by mapping the count as an index of the auxiliary array.
521521
* Method:

0 commit comments

Comments
 (0)