From 77e305b91dacbd63b38f0084fa76df9d66cd70b4 Mon Sep 17 00:00:00 2001 From: MacMullen Date: Tue, 1 Oct 2019 15:30:12 -0300 Subject: [PATCH] Added Counting Sort --- sorting/counting_sort.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sorting/counting_sort.py diff --git a/sorting/counting_sort.py b/sorting/counting_sort.py new file mode 100644 index 0000000..d6922fe --- /dev/null +++ b/sorting/counting_sort.py @@ -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) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy