# 4: The Bubble Sort¶

## Example 1: Page 83¶

In [1]:
#demonstrates bubble sort

class ArrayBub:
def __init__(self):	#special method to create objects
#with instances customized to a specific initial state

#since private instance variables don't exist in Python,
#hence using a convention: name prefixed with an underscore, to treat them as non-public part
self._v = []	#list _v

def _swap(self, one, two):	#private method
self._v[one], self._v[two] = self._v[two], self._v[one]

def insert(self, value):	#put element into array
self._v.append(value)	#insert it

def display(self):	#display array contents
print self._v	#display it

def bubbleSort(self):	#sorts the array
for out in reversed(range(2, 10)):	#outer loop (backward)
for In in xrange(out):	#inner loop (forward)
#using In as inner loop variable as in is reserved in Python
if self._v[In] > self._v[In + 1]:	#out of order?
self._swap(In, In + 1)	#swap them
#end bubbleSort()
#end class ArrayBub

arr = ArrayBub()	#create the array

arr.insert(77)	#insert 10 items
arr.insert(99)
arr.insert(44)
arr.insert(55)
arr.insert(22)
arr.insert(88)
arr.insert(11)
arr.insert(00)
arr.insert(66)
arr.insert(33)

arr.display()	#display items
arr.bubbleSort()	#bubble sort them
arr.display()	#display them again
#end

[77, 99, 44, 55, 22, 88, 11, 0, 66, 33]
[0, 11, 22, 33, 44, 55, 66, 77, 88, 99]


## Example 2: Page 85¶

In [2]:
def bubbleSort(self):	#sorts the array
for out in reversed(range(2, 10)):	#outer loop (backward)
for In in xrange(out):	#inner loop (forward)
#using In as inner loop variable as in is reserved in Python
if self._v[In] > self._v[In + 1]:	#out of order?
self._swap(In, In + 1)	#swap them
#end bubbleSort()