O'Reilly logo

A Common-Sense Guide to Data Structures and Algorithms by Jay Wengrow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Bubble Sort Implemented

Here’s an implementation of Bubble Sort in Python:

 def​ ​bubble_sort​(list):
  unsorted_until_index = len(list) - 1
  sorted = False
 
 while​ ​not​ sorted:
  sorted = True
 for​ i ​in​ range(unsorted_until_index):
 if​ list[i] > list[i+1]:
  sorted = False
  list[i], list[i+1] = list[i+1], list[i]
  unsorted_until_index = unsorted_until_index - 1
 
 list = [65, 55, 45, 35, 25, 15, 10]
 bubble_sort(list)
 print​ list

Let’s break this down line by line. We’ll first present the line of code, followed by its explanation.

 unsorted_until_index = len(list) - 1

We keep track of up to which index is still unsorted with the unsorted_until_index variable. At the beginning, the array is totally unsorted, so we initialize ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required