

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Sorting Algorithms
incomplete
2: Bubble Sort
incomplete
3: Bubble Sort Big O
incomplete
4: Why Bubble Sort?
incomplete
5: Merge Sort
incomplete
6: Merge Sort Big O
incomplete
7: Why Merge Sort?
incomplete
8: Insertion Sort
incomplete
9: Insertion Sort Big O
incomplete
10: Why Use Insertion Sort?
incomplete
11: Quicksort
incomplete
12: Quicksort Big O
incomplete
13: Fixing Quicksort
incomplete
14: Why Use Quicksort?
incomplete
15: Selection Sort
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Wait, if the standard sorted() function exists, why should we learn to write a sorting algorithm from scratch?
In all seriousness, in this chapter we'll be building some of the most famous sorting algorithms from scratch because:
It's good to understand how they work under the hood
It's great algorithmic thinking practice
It's fun! (at least for me)
Bubble sort is a very basic sorting algorithm named for the way elements "bubble up" to the top of the list.
Bubble sort repeatedly steps through a slice and compares adjacent elements, swapping them if they are out of order. It continues to loop over the slice until the whole list is completely sorted. Here's the pseudocode:
Set swapping to True
Set end to the length of the input list
While swapping is True:
Set swapping to False
For i from the 2nd element to end:
If the (i-1)th element of the input list is greater than the ith element:
Swap the (i-1)th element and the ith element
Set swapping to True
Decrement end by one
Return the sorted list
Try stepping through a small example:
While our avocado toast influencers were happy with our search functionality, now they want to be able to sort all their followers by follower count. Bubble sort is a straightforward sorting algorithm that we can implement quickly, so let's do that!
Complete the bubble_sort function according to the described algorithm above.