def bubbleSort(alist):
item = len(alist)-1
while item > 0:
for sort_item in range(0,item):
#compare with the adjacent element
if alist[sort_item]>=alist[sort_item+1]:
#swap both elements
alist[sort_item], alist[sort_item+1] = alist[sort_item+1], alist[sort_item]
item-=1
alist = [1,66,100,3,50,72]
bubbleSort(alist)
print(alist)
The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs.
Figure 1 shows the first pass of a bubble sort. The shaded items are being compared to see if they are out of order. If there are n items in the list, then there are n−1n−1 pairs of items that need to be compared on the first pass. It is important to note that once the largest value in the list is part of a pair, it will continually be moved along until the pass is complete.
At the start of the second pass, the largest value is now in place. There are n−1n−1 items left to sort, meaning that there will be n−2n−2 pairs. Since each pass places the next largest value in place, the total number of passes necessary will be n−1n−1. After completing the n−1n−1 passes, the smallest item must be in the correct position with no further processing required.
In Python, it is possible to perform simultaneous assignment. The statement a,b=b,a
will result in two assignment statements being done at the same time (see Figure 2). Using simultaneous assignment, the exchange operation can be done in one statement.