Bubble Sort¶

Ahmed Moustafa

Bubble Sort¶

Bubble Sort is a simple sorting algorithm that repeatedly steps through a list of elements, compares adjacent elements, and swaps them if they are in the wrong order. The algorithm gets its name from the way smaller elements "bubble" to the top of the list as the algorithm executes.

The algorithm works by comparing each pair of adjacent elements in the list from left to right, and swapping them if they are in the wrong order. This process is repeated multiple times until the list is fully sorted.

The basic algorithm:¶

  1. Starting at the beginning of the list, compare each pair of adjacent elements.
  2. If the elements are in the wrong order (i.e., the first element is greater than the second), swap them.
  3. Continue stepping through the list and comparing adjacent elements, until the end of the list is reached.

Repeat steps 1-3 until no more swaps are needed, indicating that the list is sorted.

Bubble Sort Activity¶

  • We need 7-10 student volunteers of different heights to stand in a row at the front of the class. Volunteers can stand in any order to start.

  • Then we will use the Bubble Sort algorithm to sort the volunteers by height from shortest to tallest.

Bubble Sort in Python¶

Write a Python program to perform a bubble sort on the following list, and display the sorted list as the output

items = [5, 3, 8, 6, 7, 2]

Bubble Sort in Python - Solution¶

[2, 3, 5, 6, 7, 8]