From 1204e6f93c27e0bae8039ccbdb7015727f591d94 Mon Sep 17 00:00:00 2001 From: Skullheadx <704277@pdsb.net> Date: Tue, 24 Jan 2023 19:05:04 -0500 Subject: [PATCH] fix bubble sort --- sorting_algorithms/bubble_sort.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/sorting_algorithms/bubble_sort.py b/sorting_algorithms/bubble_sort.py index 669ceba..e387e2f 100644 --- a/sorting_algorithms/bubble_sort.py +++ b/sorting_algorithms/bubble_sort.py @@ -3,9 +3,12 @@ from utils import swap def bubble_sort(array): - for index1 in range(len(array)): # loop through each element - for index2 in range(index1, len(array)): # loop through each of the next elements - if array[index2] < array[index1]: # if lesser, then swap - swap(array, index1, index2) + for top in range(len(array) - 1, 0, -1): # loop through each element from end + is_sorted = True # to end early if already sorted + for index in range(top): # loop through each of elements until reach top + if array[index] > array[index + 1]: # if greater, swap + swap(array, index, index + 1) # swap with next + is_sorted = False # reset to not sorted + if is_sorted: # break out if already sorted + break return array # return sorted array - -- 2.54.0