Skip to Content
Course content

406: Implementing Common Sorting Algorithms

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're standing in front of a bookshelf where someone has shoved books back in completely at random. You want to organize them by height, from shortest to tallest. You don't have a magic wand to snap them into place; you have to move them one by one. Depending on how you decide to tackle this—whether you just swap two adjacent books or pick one book and slide it into a growing "sorted" section—you're essentially implementing a sorting algorithm.

In the real world, you'll almost always use Python's built-in .sort() or sorted() functions. They use Timsort, which is incredibly efficient. But as an engineer, you need to understand the mechanics under the hood. If you're in a technical interview or optimizing a very specific piece of hardware, you can't just rely on the built-in magic. You need to know how to manipulate the data yourself.

The Simple Swap of Bubble Sort

Think of Bubble Sort as the "low-effort" approach. You start at the beginning of your bookshelf, look at the first two books, and if the left one is taller than the right one, you swap them. Then you move to the next pair. By the time you reach the end of the shelf, the tallest book has "bubbled up" to the very last position. You then repeat the whole process for the remaining books.

def bubble_sort(data):
    n = len(data)
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            if data[j] > data[j + 1]:
                # The classic Python swap
                data[j], data[j + 1] = data[j + 1], data[j]
    return data

# Example: Book heights in cm
books = [25, 12, 30, 18, 10]
print(bubble_sort(books)) # Output: [10, 12, 18, 25, 30]

It's not fast—it's O(n²), which is a fancy way of saying it slows down drastically as your list grows—but it's the easiest one to visualize.

Building a Sorted Pile with Insertion Sort

Insertion Sort is how most of us actually sort a hand of playing cards. You pick up one card from the unsorted pile and "insert" it into the correct spot in your sorted hand. You shift the larger cards to the right to make a gap for the new card. You aren't just swapping neighbors; you're finding the exact right home for each element as you go.

def insertion_sort(data):
    for i in range(1, len(data)):
        key = data[i]
        j = i - 1
        # Move elements of data[0..i-1] that are greater than key
        # to one position ahead of their current position
        while j >= 0 and key < data[j]:
            data[j + 1] = data[j]
            j -= 1
        data[j + 1] = key
    return data

# Example: Book heights in cm
books = [25, 12, 30, 18, 10]
print(insertion_sort(books)) # Output: [10, 12, 18, 25, 30]

I personally find this one more intuitive than Bubble Sort. It's still O(n²) in the worst case, but if the list is already "almost sorted," it's surprisingly efficient.

Dividing and Conquering with Quick Sort

Now we're getting into the heavy lifting. Quick Sort uses a strategy called "Divide and Conquer." Instead of shuffling the whole list, you pick one book as a "pivot." You move every book shorter than the pivot to the left and every book taller than the pivot to the right. Now you have two smaller, unsorted piles. You just repeat that process for those piles until everything is sorted.

def quick_sort(data):
    if len(data) <= 1:
        return data
    
    # We'll pick the middle element as the pivot
    pivot = data[len(data) // 2]
    
    left = [x for x in data if x < pivot]
    middle = [x for x in data if x == pivot]
    right = [x for x in data if x > pivot]
    
    # Recursively sort the left and right, then join them
    return quick_sort(left) + middle + quick_sort(right)

# Example: Book heights in cm
books = [25, 12, 30, 18, 10]
print(quick_sort(books)) # Output: [10, 12, 18, 25, 30]

This is where we see a massive performance jump. On average, Quick Sort runs in O(n log n) time. The "magic" here is recursion—the function calling itself to break a big problem into tiny, manageable pieces.




📋 Practical Task

Implementing a Custom Grade-Book Sorter

You've been handed a list of student scores, but they've been entered out of order. Instead of using the built-in sorted() function, you need to implement a sorting mechanism from scratch to ensure you understand how the data is moving.

Your Task:
Create a function called sort_student_scores that takes a list of integers (scores) and uses the Insertion Sort algorithm to return the scores in ascending order. After implementing the function, test it with the following list: [88, 72, 95, 60, 81, 99, 45].

Requirements:

  • The function must modify the list in-place or return a new sorted list using the Insertion Sort logic (shifting elements to create a gap).
  • Do not use .sort() or sorted().
  • Print the final sorted list to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.