Ravvar597
Ravvar597

Reputation: 39

Bubble sorting algorithm while loop functionality

For the following sorting algorithm in Python, I am not understanding how the while loop functions. Immediately after the line "while sortingComplete is not True:" is the line sortingComplete = True. Doesn't the latter line not meet the condition of the while loop and therefore it should exit out of the while loop? Why does the code continue to execute even though sortingComplete was changed to True in the very next line?

def main():
    sort_list()

def sort_list():
    my_list = [3,4,5,6,4,3,2,5,6,7,8,6,4,3,5,4,4,5,6]
    print "my_list:       ", my_list
    sortingComplete = False
    while sortingComplete is not True:
        sortingComplete = True
        for number in range(len(my_list)-1):
            if my_list[number+1] < my_list[number]:
                sortingComplete = False
                my_list[number], my_list[number+1] = my_list[number+1], my_list[number]

print "Sorted my_list:", my_list

if __name__ == '__main__':
    main()

Upvotes: 0

Views: 635

Answers (1)

IBeACoder
IBeACoder

Reputation: 111

The way loops work is once you enter a loop (that is once the conditions for the loop are satisfied) we perform all the instructions/statements in the loop before we again check if now the conditions are met to exit the loop.

In this case before we enter the while loop the condition sortingComplete is set to False. So even though the next line sortingComplete = True changes the value of sortingComplete variable we still have the rest of the statements to go before the we can check if conditions are met or not to exit the loop. Your while loop has another loop inside, the for loop.

The for loop goes through the array at each position number by number until the second last position. Each time checking if the current position number is larger in value to the next position number in the my_list array (I am assuming you understand the how bubble sort works so I am not going too much in detail). Until the sorting of the array is complete and perfect the if statement in the for loop will also be true and this if statement always changes the value of sortingComplete to False.

When we exit the for loop (when number = size of my_list array - 1) we reach the end of the while loop, where because of the if statement in the for loop the value of sortingComplete is now set to False so when it is time to check the while loop condition (if sortingComplete not True) the code repeats since sortingComplete = False.

The while loop ends when my_list array is sorted in an ascending order. That is the if statement conditions in the for are never met (never true), meaning the current position number value is always less or equal than the next position number value in the my_list array.

Hope this clears things up for you.

Upvotes: 1

Related Questions