Search This Blog

Thursday, June 11, 2009

Python Bubble Sort

#KEY: compare j, j+1 till the end of array, and do this iteration in len(array) times

def swap(a,index1, index2):
temp = a[index1]
a[index1] = a[index2]
a[index2] = temp

array = [9,4,1,2,5,3,6,8,7,0]

for i in range(len(array)):
j = 0
while j+1 < len(array):
if array[j] < array[j+1]:
swap(array, j, j+1)
j = j + 1

for a in array:
print a,

No comments: