From 80e460b22a8331174e90adb567cdbebafe7e1426 Mon Sep 17 00:00:00 2001 From: Andrea Petrocchi Date: Tue, 27 Aug 2024 17:33:24 +0200 Subject: [PATCH] Enhancement: Implement bubble sort Fix #9. --- src/listwiz/sorting.py | 23 +++++++++++++++++++++-- tests/test_sorting.py | 11 +++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/listwiz/sorting.py b/src/listwiz/sorting.py index 0d379f8..15f0ea1 100644 --- a/src/listwiz/sorting.py +++ b/src/listwiz/sorting.py @@ -47,8 +47,27 @@ def merge_sort(l): def bubble_sort(l): - # We should provide bubble sort as well! - raise NotImplementedError + """Bubble sort algorithm. + + Parameters + ---------- + l : list + The list to sort + + Returns + ------- + sorted_list + """ + n = len(l) + if n <= 1: + return l + + for i in range(n): + for j in range(n-1-i): + if l[j] > l[j+1]: + l[j], l[j+1] = l[j+1], l[j] + + return l def selection_sort(l): diff --git a/tests/test_sorting.py b/tests/test_sorting.py index f7d41d1..a237e1d 100644 --- a/tests/test_sorting.py +++ b/tests/test_sorting.py @@ -21,8 +21,15 @@ def test_mergesort_empty(): def test_bubble_sort(): - # Stub for basic bubble sort tests, see issue #9 - pass + # Test even sized list: + l = [3, 2, 1, 5, 4, 6] + res = lws.bubble_sort(l) + assert res == [1, 2, 3, 4, 5, 6] + + # Test odd sized list: + l = [5, 4, 3, 2, 1] + res = lws.bubble_sort(l) + assert res == [1, 2, 3, 4, 5] def test_selection_sort():