Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page