This is my bubble sort in python put I cannot seem to find the problem.
I am looking to start creating more complex sorting algorithms, but I must first understand why my bubble sort is not functioning.
The assert is inserted to crash the program if it does not sort it correctly (which has happened every time I have run it (including debugging)
N=5000
#function to sort a list
def bubble_sort(numbers):
to_go = len(list_n)
while to_go != 0:
newn = 0
for i in range(1, to_go):
if list_n[i-1] > list_n[i]:
swap(i-1, i)
newn = i
to_go = newn
def swap(item_1, item_2):
list_n[item_1], list_n[item_2] = list_n[item_2], list_n[item_1]
list_n = []
for e in range(0,N):
list_n.append(random.randint(1,N-1))
copy = list_n[:]
#time the sorting routine
t1 = time.clock()
bubble_sort(copy)
t2 = time.clock()
#make sure the list was sorted correctly
list_n.sort()
assert(list_n==copy)
#print how long the function took to do the sort
print 'mySort took', t2-t1, 'seconds.'
The problem is basically that you pass the list to sort as numbers
to the bubble_sort
function, but inside the function, you never use that parameter.
You should replace all occurrences of list_n
with numbers
in bubble_sort
, and also pass that as an additional parameter to the swap
function, so that you're actually swapping the numbers in the list you're working on instead of the global variable list_n
.