From 2f8d756aa297088e6b1e86274fcfca1f0e8d8cfc Mon Sep 17 00:00:00 2001 From: Nils Liebreich <nilsl99@zedat.fu-berlin.de> Date: Wed, 2 Nov 2022 14:04:43 +0100 Subject: [PATCH] Implemented Countingsort --- Aufgabe02.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Aufgabe02.py b/Aufgabe02.py index a909e10..7d0f6f0 100644 --- a/Aufgabe02.py +++ b/Aufgabe02.py @@ -74,7 +74,7 @@ def InsertionSort(array): return sorted_array -def CountingSort(array): +def CountingSort(array, k=None): '''Sort the array by counting the ocjence of each element in the array. Parameters @@ -87,4 +87,22 @@ def CountingSort(array): sorted_array: a sorted copy of the array ''' - return + if k is None: + k = max(array) + + key_array = [0]*(k+1) + + # Zählen der Elemente + for i in array: + key_array[i] += 1 + + sorted_array = [0]*len(array) + + i = 0 + for j, k in enumerate(key_array): + while k > 0: + sorted_array[i] = j + i += 1 + k -= 1 + + return sorted_array -- GitLab