user970496
user970496

Reputation: 23

Bubble Sort Algorithm in Python - Last Number Not Sorting

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

Upvotes: 2

Views: 16296

Answers (2)

Mr C
Mr C

Reputation: 1

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.

Upvotes: 0

deontologician
deontologician

Reputation: 2814

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

Upvotes: 6

Related Questions