This lesson introduces the first of two sorting algorithms in the IB course, bubble sort. You will see why and where sorting is used in real life, become familiar with performing a bubble sort on a set of data, and investigate the efficiency of bubble sort.
Here is an algorithm from p213 for the bubble sort in pseudocode: Bubble sort algorithm
//p213Ex21 ======= Bubble sort - Lowest to Highest =======
ELEMENTS = [1, 663, 8, 2, 4, 1, 22, 66, 20, 122]
loop I from 0 to 8 // Number of elements -2
loop J from 0 to (8 - I)
if ELEMENTS[J] > ELEMENTS[J + 1] then // for ascending order
TEMP = ELEMENTS[J]
ELEMENTS[J] = ELEMENTS[J+1]
ELEMENTS[J+1] = TEMP
end if
end loop
end loop
output "Sorted elements"
output ELEMENTS
Exercises
1. Download the following text file p213 - Pseudocode example 21: Bubble sort and run it in Mr. Mulkey's p-code tool
2. Write example 21 in Python using codeskulptor3.
3. Look at Interactivepython.org - Bubble sort for a further explanation of Bubblesort and writing the code using a function.
4. Look at Python data structures and algorithms: Bubble sort, in particular, the pictorial and flowchart representations.
5. Write a version of your example 21, in the same format as the example on this website - using a function eg. def bubbleSort():
Test your program with different input lists.