From e30581d5762b4ebec2470a8b313b31fa468d8982 Mon Sep 17 00:00:00 2001 From: onyx-and-iris Date: Mon, 8 Jan 2024 11:41:17 +0000 Subject: [PATCH] add quicksort --- chapter4/quicksort.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 chapter4/quicksort.py diff --git a/chapter4/quicksort.py b/chapter4/quicksort.py new file mode 100644 index 0000000..6461ef0 --- /dev/null +++ b/chapter4/quicksort.py @@ -0,0 +1,32 @@ +def quicksort(arr): + if len(arr) < 2: + return arr + + +import logging +import random + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + + +def quicksort(arr): + # base case. arr of length 0 or 1 don't need sorting, so return them as is + if len(arr) < 2: + return arr + + pivot = arr[0] + + # split arr into 3 parts, [less] | [pivot] | [greater] + less = [i for i in arr[1:] if i <= pivot] + greater = [i for i in arr[1:] if i > pivot] + + return quicksort(less) + [pivot] + quicksort(greater) + + +LOWER = 0 +UPPER = 100 +SAMPLE_SIZE = 15 +numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE) +logging.debug(numbers) +print(quicksort(numbers))