8000 Added Counting Sort by sfmullen · Pull Request #66 · AllAlgorithms/python · GitHub
[go: up one dir, main page]

Skip to content

Added Counting Sort #66

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

Merged
merged 1 commit into from
Oct 1, 2019
Merged
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
35 changes: 35 additions & 0 deletions sorting/counting_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#
# Python implementation of counting sort.
#
#
# The All ▲lgorithms Project
#
# https://allalgorithms.com/
# https://github.com/allalgorithms/cpp
#
# Contributed by: Simon Faillace Mullen
# Github: @macmullen
#


def counting_sort(arr):
# Create the counting sort array with length equal to the maximum number
# in the list.
count_array = [0] * (max(arr) + 1)
# Count the amount of repetitions for each number.
for number in arr:
count_array[number] += 1
# Append the amount of repetitions in order.
position = 0
for index, number in enumerate(count_array):
for amount in range(count_array[index]):
arr[position] = index
position += 1


arr = [8, 5, 8, 4, 3, 3, 2, 1, 5, 5, 5, 9, 7, 7, 8, 1, 9, 3, 2]
print("Unsorted array:")
print(arr)
counting_sort(arr)
print("Sorted array:")
print(arr)
0