Bubble Sort

Swapping Values

In [1]:
l = [5,2,7,8,3,5]
In [2]:
l[3], l[5]
Out[2]:
(8, 5)
In [3]:
tmp = l[3]
l[3] = l[5]
l[5] = tmp
In [4]:
l[3], l[5]
Out[4]:
(5, 8)
In [5]:
l[3], l[5] = l[5], l[3]
In [6]:
l[3], l[5]
Out[6]:
(8, 5)

The Bubble Sort algorithm

In [12]:
%pprint
Pretty printing has been turned OFF
In [9]:
from random import sample
nums = sample(range(1000), k=20)
nums
In [7]:
def bubble_sort(alist):
    for passnum in range(len(alist)-1, 0, -1):
        for i in range(passnum):
            if alist[i] > alist[i+1]:
                #temp = alist[i]
                #alist[i] = alist[i+1]
                #alist[i+1] = temp
                alist[i], alist[i+1] = alist[i+1], alist[i]
In [15]:
bubble_sort(nums)
In [16]:
nums
Out[16]:
[148, 169, 202, 217, 347, 409, 468, 497, 545, 573, 658, 690, 739, 750, 809, 810, 816, 847, 864, 909]

Alternative Implementation

In [17]:
def bubble_sorted(alist):
    exchanges = True
    passnum = len(alist) - 1
    
    while passnum > 0 and exchanges:
        exchanges = False
        for i in range(passnum):
            if alist[i] > alist[i+1]:
                exchanges = True
                alist[i], alist[i+1] = alist[i+1], alist[i]
                
        passnum -= 1