Bubble Sort using a while loop in Python

Question:

I’ve been set a bubble sort for homework, and I’ve been trying to use a while loop. I know that it’s possible with a for loop, but I don’t really understand them and I’d like to write something that I understand.

unsorted = True
numbers = []
unsortchecker = 0
start = 0
maxlist = int(input("How many numbers should be sorted?"))
if len(numbers) == 1:
   print(1)
while len(numbers) < maxlist:
    num = input("Please enter a number: ")
    numbers.append(num)
while unsorted:
    if unsortchecker == 0:
        unsorted = False
    while start != maxlist:
        if numbers[start] > numbers[start+1]:
            replacement = numbers[start]
            replaced = numbers[start+1]
            del numbers[start]
            del numbers[start+1]
            numbers.insert(start, replaced)
            numbers.insert(start+1, replacement)
            unsortchecker = 1
            start = start + 1
            print(numbers)
      else:
          start = start + 1
          print(numbers)
print(numbers)

When I run this, it will work for the first few, and then replace different numbers to what I want, and then give back an error
IndexError: list index out of range
Any ideas?

Edited Code

unsorted = True
numbers = []
unsortchecker = 0
start = 0
maxlist = int(input("How many numbers should be sorted?"))
end = maxlist
if len(numbers) == 1:
    print(1)
while len(numbers) < maxlist:
    num = input("Please enter a number: ")
    numbers.append(num)
while unsorted:
    if unsortchecker == 0:
        unsorted = False
    start = 0
     while start < maxlist-1:
        if numbers[start] > numbers[start+1]:
            replacement = numbers[start]
            numbers[start] = numbers[start + 1]
            numbers[start + 1] = replacement
            unsortchecker = unsortchecker + 1
            start = start + 1
            print(numbers)
        else:
             maxlist = maxlist - 1
             print(numbers)
print(numbers)
Asked By: Tom

||

Answers:

For starters:

replacement = numbers[start]
replaced = numbers[start+1]
del numbers[start]
del numbers[start+1]
numbers.insert(start, replaced)
numbers.insert(start+1, replacement)

This looks like a very cumbersome way to swap the two numbers. Try this way:

replacement = numbers[start]
numbers[start] = numbers[start + 1]
numbers[start + 1] = replacement

And no need for del and insert. Understand what these three lines do: I put the value that’s at position start into the variable replacement. Then I overwrite the value at position start with the value at position start + 1. Then I overwrite the value at position start + 1 with the value in replacement, which is the old value of numbers[start].

There’s an even more efficient way (in python, anyway) to swap numbers, but it could be a bit confusing for starters.

That’s not the only problem though.

The way you have implemented BubbleSort is that you “bubble up” instead of “bubble down”. That means that after the very first pass, you now know that the largest element will be at the end of the list.

This means that instead of increasing start by 1 after the first pass, you’d have to reduce the upper end by 1.

Answered By: Lagerbaer

The bubble sort algorithm works in O(n*n) time by repeatedly swapping adjacent elements with each other to ensure sort order. Its popular publicized form with two for loops can easily be modified to replace with while loops as expressed below:

def bubbleSort(l):
    i = 0
    while i<len(l):
        j = 0
        while j<len(l)-1:
            if l[j+1] < l[j]:
                l[j], l[j+1] = l[j+1], l[j]
            j += 1
        i += 1
    return l

Python enables swapping without a temporary variable which makes the code look a lot more readable.

Answered By: Spade

At this particular line:

if numbers[start] > numbers[start+1]:

numbers[start+1] is referencing an element in your list that does not exist (outside the boundaries of the array).

while len(numbers) < maxlist:
    num = input("Please enter a number: ")
    numbers.append(num)

In this line of code, you are adding numbers to a list until your list length is equal to the max length. Let’s say maxList is equal to 10. Your list would contain 10 elements once it has exited this loop.

 while start != maxList:
        if numbers[start] > numbers[start+1]:
        #extra code here
        start = start + 1

In this while loop, you are iterating through each element of the array and incrementing the start variable each time. If say maxList is equal to 10, once start = 9, your while loop evaluates 9 != 10 (start != maxList) and proceeds. Your next if statement if numbers[start] > numbers[start+1] then tries to compare if numbers[9] > numbers[10]. Lists and array indexes in Python start at 0, therefore, when you are trying to reference the element at numbers[10], you are referencing the 11th value in the list, which doesn’t exist. This is a common “off by one” error that you will encounter often in your programming adventures! 🙂 To correct this, simply change your while loop to:

while start <= maxList:
Answered By: Preston Martin

Using a for loop with a definite number of iteration(s) is potentially wasteful. It fails to accommodate the scenario where a already sorted array is given. The for loop would blindly iterate regardless of whether the array is sorted or not.

Instead, we should introduce a flag and use a while loop. As soon as it detects no swapping, it’s done.

Answered By: 北įžŽ38fule
def bubblesort_using_whileloop():
    sorted = False
    while sorted is False:
        sorted = True
        for i in range(len(list)-1):
            if list[i] > list[i+1]:
                list[i], list[i+1] = list[i+1], list[i]
                sorted = False
Answered By: Tsuki
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.