Python 3D Academyবাংলা

Why sorting matters, and bubble sort

🌍 In real life. On sports day the PE teacher wants Class 6 standing in a line from shortest to tallest. The students are in a muddle, and the teacher has one simple rule: walk along the line, look at two students standing next to each other, and if the one in front is taller, they swap places. After one walk, the tallest student has been swapped all the way to the back. Walk again, and the second tallest reaches their place. Keep walking until a whole walk needs no swaps.

Why sorting matters. A sorted list makes many jobs easy:

  • searching: binary search (Chapter 43) only works on a sorted list
  • duplicates: equal values end up side by side, so one walk finds them
  • the smallest, the biggest, the middle: they sit at the start, the end and the centre
  • ranking: first, second, third place are just positions 0, 1, 2

That is why sorting is one of the most studied jobs in computing. This chapter builds three simple sorts by hand, and the next chapter builds the fast ones.

The idea in one sentence: bubble sort walks the list again and again, swapping any two neighbours that are in the wrong order, and each walk carries the biggest value still out of place to the end.

Its words:

  • sorted (ascending): every value is no bigger than the one after it
  • pass: one walk along the part not yet sorted
  • adjacent swap: swapping two neighbours, a[j] and a[j + 1]
  • in place: the list is sorted inside itself, with no second list
  • inversion: a pair of values in the wrong order (a bigger one before a smaller one)

Step by step:

  1. compare a[0] and a[1]; if the first is bigger, swap them
  2. move one step right and compare again, up to the end of the unsorted part
  3. the biggest value of that part is now at its end, in its final place
  4. shrink the unsorted part by one and do another pass
  5. if a pass makes no swaps at all, every neighbour is in order: stop

Watch the bars: the two being compared light gold, and a swap makes them hop past each other. Green bars are in their final place.

Why it is correct. Follow the biggest value during the first pass: whenever it is compared, it is the bigger one, so it is swapped one step right, and again, and again, until it reaches the end. So after pass 1 the biggest value is in the last place, after pass 2 the second biggest is in the second last place, and so on: after k passes the last k places are final. The unsorted part shrinks by one each pass, so after at most n − 1 passes everything is in place.

The early stop is right too: if a whole pass makes no swaps, every pair of neighbours is in order, and a list whose neighbours are all in order is sorted. Here a nearly sorted line needs only two passes:

What it costs, by counting. Pass 1 makes n − 1 comparisons, pass 2 makes n − 2, and so on down to 1. Added up, that is n(n − 1)/2 comparisons when every pass is needed:

  • 10 students: 45 comparisons
  • 100 students: 4,950
  • 1,000 students: 499,500

Ten times the students, about a hundred times the work: O(n²). Every swap fixes exactly one inversion, so the number of swaps is the number of inversions: 0 for a sorted list, n(n − 1)/2 for a list in reverse order. On a list that is already sorted, the early stop ends it after one pass of n − 1 comparisons: O(n) at best. It needs no second list: O(1) extra memory.

def bubble_sort(a):
    end = len(a) - 1
    while end > 0:
        swapped = False
        for j in range(end):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            break              # no swaps in a whole pass: sorted
        end -= 1
    return a

line = [152, 140, 147, 160, 138]
print(bubble_sort(line))

# Python's own: sorted() gives back a new list; list.sort() sorts in place
heights = [152, 140, 147, 160, 138]
print(sorted(heights), heights)
heights.sort()
print(heights)

Mistakes and edge cases.

  • for j in range(len(a)) with a[j + 1]: the last j reaches past the end, an IndexError: list index out of range; stop one early
  • >= instead of >: equal values swap for nothing, which wastes swaps and changes the order of equal values (Lesson 44.3)
  • no early stop: still correct, but a sorted list costs n(n − 1)/2 comparisons instead of n − 1
  • a = a.sort(): sort() sorts in place and gives back None, so a becomes None; use a.sort() alone, or a = sorted(a)
  • empty and one-item lists: already sorted; end starts at 0 or less, so no pass runs

Quiz

  1. One pass of bubble sort. What does this print?

    a = [4, 3, 1, 2]
    for j in range(len(a) - 1):
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]
    print(a)
  2. After the first pass of bubble sort, what is certain?

    • The biggest value is in the last place
    • The smallest value is in the first place
    • The list is sorted
  3. This crashes with IndexError. Which line is wrong?

    def bubble_sort(a):
        for end in range(len(a) - 1, 0, -1):
            for j in range(end + 1):
                if a[j] > a[j + 1]:
                    a[j], a[j + 1] = a[j + 1], a[j]
        return a
  4. Bubble sort with the early stop gets 100 values that are already sorted. How many comparisons does it make?

    • 99: one pass, no swaps, stop
    • 4,950
    • 0
  5. At worst, how does bubble sort's work grow with n values?

    • O(n²): about n²/2 comparisons
    • O(n)
    • O(n log n)

Coding tasks

  1. Write bubble_sort(a): sort the list a in place with bubble sort and return it. Stop as soon as a pass makes no swaps, so a list that is already sorted takes just one pass.

  2. Before sports day the teacher wants to know how much shuffling a line needs. Write swaps_needed(heights): how many neighbour swaps bubble sort makes to sort the list. Don't change heights itself.