Bubble Sort Algorithm in Python - Last Number Not Sorting


Question

The algorithm sorts all the numbers except the first one, and sets it as last. Please help!

def bubbleSort(numbers): # Bubble Sort Algorithm
    numbers = list(numbers)
    i = 0
    j = 0
    for i in range(len(numbers)):
        for j in range(len(numbers) - i):
            if numbers[j] < numbers[j-1]: 
                       temp = numbers[j-1]
                       numbers[j-1] = numbers[j]
                       numbers[j] = temp

    print numbers
    print numbers
1
2
2/9/2012 2:22:58 AM

Accepted Answer

The problem is that sometimes [j-1] becomes negative. In python, numbers[-1] means "get the last element in numbers". Here is a fixed version:

def bubbleSort(numbers): # Bubble Sort Algorithm
    nums = list(numbers)
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if numbers[j] < numbers[i]:
                numbers[j], numbers[i] = numbers[i], numbers[j]

    print numbers

You'll notice that it is also possible to swap numbers without a temp variable in python as well

6
2/9/2012 2:39:22 AM

I would not describe this as a 'Bubble sort' as it does not swap the list elements that are next to each other. Its more like a 'Selection sort' as it is looking through the list and comparing each element with the first then swapping the smallest number with the first.

It seems to be a bubble/selection mash-up.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon