Many computer science students are expected to perform sorting. Here is an example of doing a bubble sort in Python.
def bubble_sort(array):
# Grab the length of the array
n = len(array)
# Iterate through array from 0 to n
for i in range(len(array)):
# Iterate through array from 1 to n - i
for j in range(1, n - i):
# Now check if the element at array[j - 1] is larger than array[j]
if array[j - 1] > array[j]:
# Perform a swap of the elements
temp = array[j - 1]
array[j - 1] = array[j]
array[j] = temp
if __name__ == '__main__':
unsorted = [10, 5, 2, 3, 1]
print('Unsorted list is: ', unsorted)
bubble_sort(unsorted)
print('Sorted list is now: ', unsorted)
One thought on “Bubble Sort—Python”