From 4d2e7857b2a18cfc428fc87f02159cb7076900ea Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Wed, 2 Aug 2023 20:55:05 -0700 Subject: [PATCH] Create counting_sort.py --- sorting/counting_sort.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 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..7ee9de8 --- /dev/null +++ b/sorting/counting_sort.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + + +def counting_sort(list): + + K = max(lst) + counts = [0] * (K + 1) + for elem in lst: + counts[elem] += 1 + + starting_index = 0 + for i, count in enumerate(counts): + counts[i] = starting_index + starting_index += count + + sorted_lst = [0] * len(lst) + + for elem in lst: + + sorted_lst[counts[elem]] = elem + counts[elem] += 1 + + for i in range(len(lst)): + lst[i] = sorted_lst[i]