Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
73: Implementing Common Sorting Algorithms
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
Transactionstruct with fieldsID (int)andAmount (float64). - Write a function
SortTransactions(txs []Transaction)that sorts the slice in-place based on theAmount. - In your
mainfunction, 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
}
There are no comments for now.