The bubble sort program uses most of the elements we have discussed so far. There are variables, lists, functions, if statements, and loops. If you understand these elements as demonstrated in this program, you are ready to program. The bubble sort logic is not important. Try to see how the different elements fit together. Notice the indentations and the commands themselves. Because Python runs the commands in order from top to bottom; the defined function must be listed first.

The program starts with a function that that swaps the values in a list.

Next is a list of five numbers to be sorted.

We then initialize loop counter i and j.

While item i in the list is less than five, we will continue. (The items in the list are indexed 0 to 4.)

j is the next item in the list.

If item i is larger than item j, then we swap the items.

If item i is not larger than item j, we leave the items alone.

J is increased by one.

i is compared to the next j in the list, and compared again.

The above processes are repeated for the five numbers.

i is increased one and all the processes above repeated.

In the end we have a sorted list.

`#Functions have to be listed at top`

def myswap(a,b,alist): #Swap function

temp = alist[a]

alist[a] = alist[b]

alist[b] = temp

return alist

`mylist = [3,9,4,6,10] # List to be sorted`

i = 0

j = 0

while i < 5: # There are 5 items in list

j = i + 1

while j < 5:

if mylist[i] > mylist[j]:

mylist = myswap(i,j,mylist)

j = j + 1

i = i + 1

print(mylist)

`# Output [3, 4, 6, 9, 10]`

SALARSEN.COM

Table of Contents

Ch1-Install Python

Ch2-Install PyCharm

Ch3-Save Work

Ch4-Add Project

Ch5-Variables

Ch6-Print&Input

Ch7-Lists

Ch8-Loops

Ch9-If&Logical

Ch10-Functions

Ch11-Bubble Sort

Ch12-Plotting

Ch13-Files

Ch14-Print Format

Ch15-Dict&Comp&Zip

Ch16-Arrays

Ch17-Electrical

Ch18-Regression

Ch19-Differential

Ch20-Secant