From 2c231a25bf9a4ed19b1d5ea6e3309986c635190c Mon Sep 17 00:00:00 2001 From: Vladimir Parfinenko Date: Sat, 15 Oct 2022 10:01:02 +0700 Subject: [PATCH 1/3] Implement base sorting --- sort.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 sort.py diff --git a/sort.py b/sort.py new file mode 100644 index 0000000..5c0e3e9 --- /dev/null +++ b/sort.py @@ -0,0 +1,11 @@ +arr = [40, 4, 20, 10, 30, 6, 10] + +# selection sort: +for i in range(len(arr) - 1): + min = i + for j in range(i + 1, len(arr)): + if arr[j] < arr[min]: + min = j + arr[i], arr[min] = arr[min], arr[i] + +print(arr) From ccf6898b018f6753c8bdbb3176503c406b928551 Mon Sep 17 00:00:00 2001 From: Vladimir Parfinenko Date: Sat, 15 Oct 2022 10:12:03 +0700 Subject: [PATCH 2/3] Use better sorting algorithm However it still has quadratic complexity --- sort.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/sort.py b/sort.py index 5c0e3e9..3d7e173 100644 --- a/sort.py +++ b/sort.py @@ -1,11 +1,15 @@ arr = [40, 4, 20, 10, 30, 6, 10] -# selection sort: -for i in range(len(arr) - 1): - min = i - for j in range(i + 1, len(arr)): - if arr[j] < arr[min]: - min = j - arr[i], arr[min] = arr[min], arr[i] +# insertion sort: +for i in range(1, len(arr)): + a_i = arr[i] + j = i - 1 + while j >= 0: + if arr[j] > a_i: + arr[j + 1] = arr[j] + else: + break + j -= 1 + arr[j + 1] = a_i print(arr) From ba2edc218c7026e604a9a91c7864dd09967e2612 Mon Sep 17 00:00:00 2001 From: Vladimir Parfinenko Date: Sat, 15 Oct 2022 10:16:41 +0700 Subject: [PATCH 3/3] Make sorting more verbose --- sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sort.py b/sort.py index 3d7e173..16623a2 100644 --- a/sort.py +++ b/sort.py @@ -5,6 +5,7 @@ a_i = arr[i] j = i - 1 while j >= 0: + print("comparing {} and {}".format(arr[j], a_i])) if arr[j] > a_i: arr[j + 1] = arr[j] else: