Bubble Sort

Here is bubble sort. It goes through the list and if it sees two things next to each other in the wrong order, it swaps them. This version goes through the list once for every element in the list, just in case.

def swap(lst, a, b):
    lst[a], lst[b] = lst[b], lst[a]

def bubblesort(lst):
    for y in range(len(lst) - 1):
        for x in range(len(lst) - 1):
            if lst[x] > lst[x + 1]:
                swap(lst, x, x + 1)

If a list is mostly sorted, it will end up going through the list many times after it is completely sorted. Here is a version that stops when the list is sorted. It knows it is sorted if no swaps were made when it went through the list.

def bubblesort(lst):
    done = False
    while not done:
        done = True
        for x in range(len(lst) - 1):
            if lst[x] > lst[x + 1]:
                swap(lst, x, x + 1)
                done = False

Post a Comment

Your email is never published nor shared.