Classic: Bubble Sort

Question

Please implement Bubble Sort.


Answer

Bubble Sort is a basic and simple sorting algorithm. It has O(n^2) complexity.

def bubble_sort(arr):
  n = len(arr)
  for i in range(n):
    for j in range(0, n-i-1):
      # if not in ascending order, swap
      if arr[j] > arr[j+1]:
        arr[j], arr[j+1] = arr[j+1], arr[j]
  return arr

# call the function
input = [8, 3, 2, 8, 5, -1, 4, 6, 7, 2, 6, 4, 0, 9, 6, 5, 8]
print(bubble_sort(input))

👍 Have fun while coding with Python!

👌 Please subscribe to receive notifications on future challenges.

💬 If you have any questions simply write a comment down below.

Leave a Comment