Skip to content

Commit 02246d3

Browse files
Shruti ShreeShruti Shree
Shruti Shree
authored and
Shruti Shree
committed
added counting sort
1 parent f7b5300 commit 02246d3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Sorting/countingsort.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class CountingSort:
2+
def __init__(self, array):
3+
self.array = array
4+
5+
def sort(self):
6+
if not self.array:
7+
return []
8+
9+
# Find the maximum and minimum values
10+
max_val = max(self.array)
11+
min_val = min(self.array)
12+
range_of_elements = max_val - min_val + 1
13+
14+
# Initialize the count array
15+
count = [0] * range_of_elements
16+
output = [0] * len(self.array)
17+
18+
# Count occurrences
19+
for num in self.array:
20+
count[num - min_val] += 1
21+
22+
# Update count array to store cumulative sums
23+
for i in range(1, len(count)):
24+
count[i] += count[i - 1]
25+
26+
# Build the output array
27+
for num in reversed(self.array):
28+
output[count[num - min_val] - 1] = num
29+
count[num - min_val] -= 1
30+
31+
# Copy sorted elements back to original array
32+
self.array[:] = output
33+
34+
def get_sorted_array(self):
35+
return self.array
36+
37+
38+
# Example Usage:
39+
arr = [4, 2, 2, 8, 3, 3, 1]
40+
cs = CountingSort(arr)
41+
cs.sort()
42+
print("Sorted Array:", cs.get_sorted_array())

0 commit comments

Comments
 (0)