Created
April 29, 2023 05:11
-
-
Save nktnlx/a976bfd012cae21dd7b104c75fd7c46b to your computer and use it in GitHub Desktop.
bubble sort implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bubble_sort(lst): | |
# Get the length of the input list | |
cnt = len(lst) | |
# Iterate over the list until all elements are sorted | |
while cnt > 0: | |
# Iterate over each element in the list | |
for i in range(1, len(lst)): | |
# Compare the current element with the previous element | |
if lst[i - 1] > lst[i]: | |
# If the previous element is larger, swap the elements | |
lst[i - 1], lst[i] = lst[i], lst[i - 1] | |
# Decrement the count to keep track of how many elements are left to sort | |
cnt -= 1 | |
# Return the sorted list | |
return lst | |
# Call the bubble_sort function with an unsorted list and print the sorted result | |
print(bubble_sort([99, 3, 2, 1, 0, 98])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment