CHAPTER 6 - PYTHON SAMPLE PROGRAM



AD

Python Bubble Sort

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]

theSurfDragon.com


Win-Python Navigation

Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays