Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added counting sort #413

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Sorting/countingsort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class CountingSort:
def __init__(self, array):
self.array = array

def sort(self):
if not self.array:
return []

# Find the maximum and minimum values
max_val = max(self.array)
min_val = min(self.array)
range_of_elements = max_val - min_val + 1

# Initialize the count array
count = [0] * range_of_elements
output = [0] * len(self.array)

# Count occurrences
for num in self.array:
count[num - min_val] += 1

# Update count array to store cumulative sums
for i in range(1, len(count)):
count[i] += count[i - 1]

# Build the output array
for num in reversed(self.array):
output[count[num - min_val] - 1] = num
count[num - min_val] -= 1

# Copy sorted elements back to original array
self.array[:] = output

def get_sorted_array(self):
return self.array


# Example Usage:
arr = [4, 2, 2, 8, 3, 3, 1]
cs = CountingSort(arr)
cs.sort()
print("Sorted Array:", cs.get_sorted_array())