Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor bubble sort implementation for improved readability and performance #6801

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 24 additions & 37 deletions code/sorting/src/bubble_sort/bubble_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,27 @@


def bubble_sort(arr):
"""
>>> arr = [5, 1, 3, 9, 2]
>>> bubble_sort(arr)
>>> arr
[1, 2, 3, 5, 9]
"""
for i in range(len(arr)):
# Terminate algorithm if no more swaps are to be carried out
is_sorted = True
for j in range(i + 1, len(arr)):
# If current(ith) element is greater than the next((i+1)th) element swap them
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
is_sorted = False
if is_sorted:
break


# Less elegant solution, but easier to follow along:
def bubble_sort(alist):
# flag to keep track of whether the list is sorted or not, initially it is set as false
is_sorted = False
# keep comparing till the list is sorted
while not is_sorted:
num_swaps = 0
# iterate through all the elements(except the last) in the list
for i in range(len(alist) - 1):
# if the current element is greater than the next element, pop it out of the list
if alist[i] > alist[i + 1]:
a = alist.pop(i + 1)
# insert the popped element to its right position in the list
alist.insert(i, a)
num_swaps += 1
# if the list is sorted, no more swaps are carried out
if num_swaps == 0:
is_sorted = True
return alist
n = len(arr)

for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

return arr


# Example usage
if __name__ == "__main__":
# Just an example list to test with
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr) # Output: [64, 34, 25, 12, 22, 11, 90]

# Run the bubble sort
bubble_sort(arr)

# Print out the sorted list
print("Sorted array:", arr) # Output: [11, 12, 22, 25, 34, 64, 90]