Skip to Content
Course content

73: Implementing Common Sorting Algorithms

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

You’ve likely already discovered the sort package in Go. For 99% of your professional work, sort.Ints() or sort.Slice() is exactly what you want. But if you're heading into a technical interview or trying to optimize a very specific piece of memory-constrained hardware, you need to understand what's happening under the hood. Sorting isn't just about "putting things in order"; it's about how you move data around in memory.

The Card Table Analogy

Imagine you're sitting at a table with a messy hand of playing cards laid out in a row. You want them sorted from lowest to highest.

  • The Bubble approach: You look at the first two cards. If the left one is higher than the right one, you swap them. Then you move to the second and third cards, swapping if needed. You keep doing this until the highest card "bubbles" all the way to the right side of the table. Then you start over from the left.
  • The Quick approach: You pick one card at random—let's call it the "pivot." You throw every card smaller than the pivot into a pile on the left and every card larger than the pivot into a pile on the right. Now you have two smaller piles. You repeat the same process for those piles until every single card is in its own tiny pile, and then you just line them up.

Bubbling Up the Largest Values

Bubble Sort is the "teaching" algorithm. It's inefficient for large sets, but it's the easiest to visualize. In Go, the beauty is how we can handle the swap. We don't need a temporary variable like you do in C or Java; we can use Go's tuple assignment to swap elements in a single line.

func BubbleSort(numbers []int) {
    n := len(numbers)
    for i := 0; i < n; i++ {
        for j := 0; j < n-i-1; j++ {
            if numbers[j] > numbers[j+1] {
                // This is the Go way to swap without a 'temp' variable
                numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
            }
        }
    }
}

Notice the n-i-1 in the inner loop. I do this because, after every full pass, the largest remaining element is guaranteed to be at the end. There's no point in checking the end of the slice over and over again.

Splitting the Problem in Half

Quick Sort is a different beast. It uses a strategy called "divide and conquer." Instead of shuffling elements one by one, it partitions the data. It's recursively calling itself, which is where a lot of developers get tripped up. The trick is to remember that the base case—the moment the recursion stops—is when the slice has a length of zero or one.

func QuickSort(numbers []int) []int {
    if len(numbers) < 2 {
        return numbers
    }

    pivot := numbers[0]
    var left, right []int

    // We start at index 1 because index 0 is our pivot
    for _, v := range numbers[1:] {
        if v < pivot {
            left = append(left, v)
        } else {
            right = append(right, v)
        }
    }

    // Recursively sort the left and right, then sandwich the pivot between them
    result := append(QuickSort(left), pivot)
    result = append(result, QuickSort(right)...)
    
    return result
}

I'll be honest with you: the implementation above is the "readable" version. It allocates new slices (left and right) on every call, which is heavy on the garbage collector. In a high-performance production environment, you'd do this "in-place" by swapping indices within the original slice, but that usually makes the code look like a math textbook. When you're starting out, focus on the logic of the partition first.

When to Actually Use These

In the real world, you will almost never write your own QuickSort from scratch in Go because the standard library uses a sophisticated hybrid called pdqsort (Pattern-Defeating QuickSort). However, implementing these yourself teaches you about time complexity. Bubble Sort is O(n²)—meaning if you double the list size, it takes four times as long. Quick Sort is generally O(n log n), which is why it's the industry standard for general-purpose sorting.




📋 Practical Task

Building a Custom Transaction Amount Sorter

You are building a financial ledger. You have a slice of Transaction structs, and you need to sort them by the Amount field in ascending order. Instead of using the sort package, you must implement a manual Bubble Sort to handle this specific logic.

Requirements:

  • Define a Transaction struct with fields ID (int) and Amount (float64).
  • Write a function SortTransactions(txs []Transaction) that sorts the slice in-place based on the Amount.
  • In your main function, create a slice of at least 5 transactions with unsorted amounts, call your sorting function, and print the result.
// Starter code:
type Transaction struct {
    ID     int
    Amount float64
}

func SortTransactions(txs []Transaction) {
    // Your implementation here
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.