August 2017
Intermediate to advanced
222 pages
5h 3m
English
Here’s an implementation of Bubble Sort in Python:
| | def bubble_sort(list): |
| | unsorted_until_index = len(list) - 1 |
| | sorted = False |
| | |
| | while not sorted: |
| | sorted = True |
| | for i in range(unsorted_until_index): |
| | if list[i] > list[i+1]: |
| | sorted = False |
| | list[i], list[i+1] = list[i+1], list[i] |
| | unsorted_until_index = unsorted_until_index - 1 |
| | |
| | list = [65, 55, 45, 35, 25, 15, 10] |
| | bubble_sort(list) |
| | print list |
Let’s break this down line by line. We’ll first present the line of code, followed by its explanation.
| | unsorted_until_index = len(list) - 1 |
We keep track of up to which index is still unsorted with the unsorted_until_index variable. At the beginning, the array is totally unsorted, so we initialize ...