Search code examples
pythonpython-2.7bubble-sort

Bubble sort error with nested (high scores) list - python


For my software major work I have to create a program. In summary, the high scores list needs to be sorted before it can be written to file. To do this, I am using a bubble sort and I can't use the inbuilt sort function. The text file that the data is being read from is stored in a nested list. The text file looks like this:

NameOne
10
NameTwo
15
NameThree
9

This is the bubble sort code I have but does not work:

b_not_sorted = True
while b_not_sorted:
    counter = 0
    b_not_sorted = False
    for counter in range(len(highest_scores) - 1):
        if highest_scores[counter] < highest_scores[counter + 1]:
            b_not_sorted = True
            highest_scores[counter], highest_scores[counter+1] = highest_scores[counter+1], highest_scores[counter]
        counter = counter + 1

I need the scores to be sorted from highest to lowest. Any help would be greatly appreciated and you will be credited appropriately in my program credits :). Thanks.


Solution

  • Here's a hint:

    Check how many times your outer while loop is running. It should be running more than once, correct? What will always happen that causes the loop to exit, no matter what?

    Try going through the code line by line and seeing what happens at every point.

    The statement b_not_sorted = False at the end of the outer loop results in the outer loop exiting after executing only once. You need to move that statement to another part of your code. Try changing the name of b_not_sorted to I_still_need_to_go_through_the_list in your head:

    Obviously in the first line:

    while I_still_need_to_go_through_the_list:
    

    it should be True, since you haven't gone over the list at all. You don't know if it's in order or not.

    and after the line:

    if highest_scores[counter] < highest_scores[counter + 1]:
    

    Of course then we still need to make another pass, since we just made a change to the list and need to make sure no further changes are needed.

    But what if no changes are made? I_still_need_to_go_through_the_list should be False then. Hmmm. If we put I_still_need_to_go_through_the_list = False right before the for loop, then it will be False unless we make changes to the list, which is exactly what we want.