Skip to Content
Course content

123: Implementing Common Sorting Algorithms

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

Imagine you've got a messy bookshelf where the books are in no particular order, but you want them alphabetized. If you're not thinking about efficiency, you might just look at the first two books, swap them if they're in the wrong order, and then move one book to the right and repeat. You'd keep walking down the line, swapping pairs, until the "heaviest" (or last alphabetically) book eventually floats all the way to the end of the shelf. That's exactly how a Bubble Sort works.

Now, if you had a massive library, that approach would be a nightmare. Instead, you'd probably pick one random book (a pivot), put everything that comes before it in one pile and everything that comes after it in another. Then, you'd just repeat that process for the two smaller piles. That's the essence of Quick Sort. The core difference is whether you're grinding through the list one pair at a time or strategically splitting the problem in half.

The Intuitive Slog of Bubble Sort

I'll be honest with you: you will almost never use Bubble Sort in a professional production environment. It's slow. But I always insist that students implement it once because it teaches you how to manipulate array indices and perform swaps—the bread and butter of data manipulation.

public void BubbleSort(int[] numbers)
{
    int n = numbers.Length;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - i - 1; j++)
        {
            if (numbers[j] > numbers[j + 1])
            {
                // The classic swap pattern
                int temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
            }
        }
    }
}

Notice that inner loop condition n - i - 1. I used that because after each full pass, the largest element is already locked into its final position at the end. There's no point in checking it again. It's a small optimization, but it's the kind of detail that separates a coder from an engineer.

Dividing and Conquering with Quick Sort

Quick Sort is a different beast. It uses recursion, which can feel a bit like a mind-bend the first time you see it. The goal here is to pick a "pivot" and partition the array around it. Everything smaller goes left, everything larger goes right.

public void QuickSort(int[] array, int left, int right)
{
    if (left < right)
    {
        int pivotIndex = Partition(array, left, right);
        
        // Recursively sort the elements before and after the pivot
        QuickSort(array, left, pivotIndex - 1);
        QuickSort(array, pivotIndex + 1, right);
    }
}

private int Partition(int[] array, int left, int right)
{
    int pivot = array[right]; 
    int i = left - 1;

    for (int j = left; j < right; j++)
    {
        if (array[j] <= pivot)
        {
            i++;
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    int tempPivot = array[i + 1];
    array[i + 1] = array[right];
    array[right] = tempPivot;
    
    return i + 1;
}

In this implementation, I'm using the last element as the pivot. It's a simple choice, though in a real-world scenario, picking a random pivot helps avoid the "worst-case" performance where the array is already sorted. When you run this, you're not just moving items; you're narrowing the scope of the problem until it's so small it's solved by default.

Knowing When to Stop Rolling Your Own

Here is the most important piece of advice I can give you: just because you can implement these doesn't mean you should in a real project. C# gives you Array.Sort() and LINQ's OrderBy(). Under the hood, .NET uses an Introspective Sort—a hybrid that starts with Quick Sort and switches to Heap Sort or Insertion Sort depending on the data size. It's significantly more optimized than anything we've written here.

We implement these to understand time complexity (Big O) and memory management. Once you understand how a pivot works or why nested loops kill performance, you'll have a much better intuition for why OrderBy() behaves the way it does.




📋 Practical Task

Gaming Leaderboard Score Sorter

You are building a high-score table for a retro arcade game. You have an array of integers representing player scores, but they are arriving in a random, unsorted order. Instead of using the built-in Array.Sort(), your task is to implement a custom sorting method to organize these scores from highest to lowest.

Requirements:

  • Create a class called LeaderboardManager.
  • Implement a method called SortScoresDescending(int[] scores).
  • Use either the Bubble Sort or Quick Sort logic from this lesson, but modify the comparison logic so the largest numbers appear first (Descending order).
  • In your Main method, initialize an array with these values: [450, 1200, 800, 2100, 150, 900].
  • Print the sorted array to the console to verify the result is [2100, 1200, 900, 800, 450, 150].
Rating
0 0

There are no comments for now.

to be the first to leave a comment.