Go sorting programs put data in order, such as products by price, students by marks or names from A to Z. In this post, you will write the classic sorting algorithms by hand (bubble, selection, insertion, merge, quick and counting sort) and then use Go’s built-in slices.Sort and slices.SortFunc for real work. Every program shows its exact output, and the interview section covers speed, stability and tricky sort questions.
This post builds on our Go slice programs, because every sort here works on a slice. We also use recursion from our Go number programs for merge sort and quick sort. All programs were tested on Go 1.27.
What are Go Sorting Programs?
Go sorting programs arrange the items of a slice in order, usually from smallest to largest. You can write the algorithm yourself to learn how it works, or call the standard library to sort fast and safely.
Think of sorting a deck of playing cards. Some people pick the smallest card each time, others slide each new card into its place, and others split the deck in half and merge the piles. Each way is a different sorting algorithm, and some are much faster than others.
Why Go Sorting Programs Matter
Sorted data is easier to search, show and compare, which is why Go sorting programs appear in so many apps. For example, an online shop sorts by price, a leaderboard sorts by score and a report sorts by date. Interviewers also love sorting, because it shows if you understand loops, recursion and time complexity.
- Interviews: you may be asked to write bubble, insertion, merge or quick sort by hand.
- Real code: you will use
slices.Sortandslices.SortFuncalmost every week. - Algorithms: binary search and many other tricks need sorted data first.
How Go Sorting Programs Work
Most Go sorting programs repeat two steps: compare two items and swap them if they are in the wrong order. The algorithms differ in which pairs they compare and how often.

The table below compares the algorithms in this post.
| Algorithm | Average time | Extra memory | Stable |
|---|---|---|---|
| Bubble sort | O(n squared) | O(1) | Yes |
| Selection sort | O(n squared) | O(1) | No |
| Insertion sort | O(n squared) | O(1) | Yes |
| Merge sort | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(log n) | No |
| Counting sort | O(n + k) | O(k) | Yes |
| slices.Sort (pdqsort) | O(n log n) | O(log n) | No |
A sort is stable when equal items keep their original order. This matters when you sort records by one field after another.
Simple Go Sorting Programs
These first four Go sorting programs are easy to write and good for small lists.
Program 1: Compare and Swap Two Items
Every sort is built from one small step. You compare two items, and if they are in the wrong order, you swap them.
package main
import "fmt"
func main() {
// := creates a variable and gives it a value in one go.
numbers := []int{9, 4}
fmt.Println("Before:", numbers)
// Is the first item bigger than the second? Then they are in the wrong order.
if numbers[0] > numbers[1] {
// Swap: Go reads both right-side values first, then sets both left sides.
numbers[0], numbers[1] = numbers[1], numbers[0]
}
fmt.Println("After:", numbers)
}
Before: [9 4]
After: [4 9]
The program checks whether 9 is bigger than 4. It is, so the two items swap places. Bubble sort below repeats this exact step over the whole slice.
Program 2: Bubble Sort
Bubble sort swaps neighbours that are out of order. You stop early if a pass makes no swaps.
package main
import "fmt"
// bubbleSort sorts numbers from small to large by swapping neighbours.
func bubbleSort(numbers []int) {
// Each pass moves the largest remaining number to the end.
for i := 0; i < len(numbers)-1; i++ {
swapped := false
// The last i items are already in place, so skip them.
for j := 0; j < len(numbers)-1-i; j++ {
if numbers[j] > numbers[j+1] {
numbers[j], numbers[j+1] = numbers[j+1], numbers[j] // swap
swapped = true
}
}
fmt.Println("Pass", i+1, numbers)
// No swaps means the slice is already sorted.
if !swapped {
break
}
}
}
func main() {
numbers := []int{5, 1, 4, 2, 8}
bubbleSort(numbers) // a slice shares its data, so the function sorts our numbers
fmt.Println("Sorted:", numbers)
}
Pass 1 [1 4 2 5 8]
Pass 2 [1 2 4 5 8]
Pass 3 [1 2 4 5 8]
Sorted: [1 2 4 5 8]
The inner loop compares each pair of neighbours and swaps them if needed. After each pass, the largest remaining number sits at the end. Pass 3 made no swaps, so the loop stopped early.
Program 3: Selection Sort
Selection sort finds the smallest item and moves it to the front, one position at a time.
package main
import "fmt"
// selectionSort puts the smallest remaining number at the front on each pass.
func selectionSort(numbers []int) {
for i := 0; i < len(numbers)-1; i++ {
// Step 1: find the position of the smallest number from i to the end.
smallestIndex := i
for j := i + 1; j < len(numbers); j++ {
if numbers[j] < numbers[smallestIndex] {
smallestIndex = j
}
}
// Step 2: swap it into position i.
numbers[i], numbers[smallestIndex] = numbers[smallestIndex], numbers[i]
}
}
func main() {
numbers := []int{64, 25, 12, 22, 11}
selectionSort(numbers)
fmt.Println(numbers)
}
[11 12 22 25 64]
On each pass, the inner loop finds the smallest number that is left. Then one swap moves it to the front of the unsorted part. It makes at most n – 1 swaps, but it always does about n squared comparisons.
Program 4: Insertion Sort
Insertion sort takes each item and slides it left until it fits, like sorting cards in your hand.
package main
import "fmt"
// insertionSort slides each number left until it sits in the right place.
func insertionSort(numbers []int) {
for i := 1; i < len(numbers); i++ {
// Step 1: pick up the current card.
current := numbers[i]
// Step 2: move bigger numbers one place to the right.
j := i - 1
for j >= 0 && numbers[j] > current {
numbers[j+1] = numbers[j]
j--
}
// Step 3: drop the card into the gap.
numbers[j+1] = current
}
}
func main() {
numbers := []int{12, 11, 13, 5, 6}
insertionSort(numbers)
fmt.Println(numbers)
}
[5 6 11 12 13]
You hold current and shift every bigger number one place right. When the loop stops, the gap is the right spot for current. Insertion sort is very fast on data that is almost sorted.
Fast Go Sorting Programs
These Go sorting programs split the work and run in O(n log n) time.
Program 5: Merge Sort
Merge sort splits the slice in half, sorts each half, then merges the two sorted halves.
package main
import "fmt"
// mergeSort returns a new sorted slice. It calls itself on each half (recursion).
func mergeSort(numbers []int) []int {
// A slice with 0 or 1 items is already sorted.
if len(numbers) <= 1 {
return numbers
}
middle := len(numbers) / 2
left := mergeSort(numbers[:middle]) // [:middle] is the first half
right := mergeSort(numbers[middle:]) // [middle:] is the second half
return merge(left, right)
}
// merge joins two sorted slices into one sorted slice.
func merge(left, right []int) []int {
// make creates an empty slice with room for all items.
result := make([]int, 0, len(left)+len(right))
i, j := 0, 0
// Take the smaller front item from either side, until one side runs out.
for i < len(left) && j < len(right) {
if left[i] <= right[j] {
result = append(result, left[i])
i++
} else {
result = append(result, right[j])
j++
}
}
// Add whatever is left. ... spreads a slice into separate values.
result = append(result, left[i:]...)
result = append(result, right[j:]...)
return result
}
func main() {
fmt.Println(mergeSort([]int{38, 27, 43, 3, 9, 82, 10}))
}
[3 9 10 27 38 43 82]
mergeSort keeps splitting until each piece has one item. Then merge joins two sorted pieces by always taking the smaller front item. Using <= keeps equal items in order, which makes merge sort stable.
Program 6: Quick Sort
Quick sort picks a pivot, puts smaller items on its left and bigger items on its right, then repeats on each side.
package main
import "fmt"
// quickSort sorts numbers in place around a pivot, then sorts each side.
func quickSort(numbers []int) {
if len(numbers) < 2 {
return
}
// Step 1: use the last item as the pivot.
last := len(numbers) - 1
pivot := numbers[last]
// Step 2: move every number smaller than the pivot to the front.
// boundary is where the next small number should go.
boundary := 0
for j := 0; j < last; j++ {
if numbers[j] < pivot {
numbers[boundary], numbers[j] = numbers[j], numbers[boundary]
boundary++
}
}
// Step 3: put the pivot right after the small numbers.
numbers[boundary], numbers[last] = numbers[last], numbers[boundary]
// Step 4: sort the left side and the right side the same way.
quickSort(numbers[:boundary])
quickSort(numbers[boundary+1:])
}
func main() {
numbers := []int{10, 80, 30, 90, 40, 50, 70}
quickSort(numbers)
fmt.Println(numbers)
}
[10 30 40 50 70 80 90]
The pivot here is 70, so all smaller numbers move to the front. Then 70 goes right after them, and each side is sorted the same way. Its worst case is O(n squared) on already sorted data, so real libraries choose the pivot more carefully.
Program 7: Counting Sort
When values sit in a small range, counting sort beats every comparison sort.
package main
import "fmt"
func main() {
ages := []int{5, 3, 8, 3, 1, 5, 3, 9}
// Step 1: count how many times each age appears.
// count[3] will hold how many 3s there are.
var count [10]int
for _, age := range ages { // _ skips the index we do not need
count[age]++
}
// Step 2: write each age as many times as it was counted.
sorted := make([]int, 0, len(ages))
for age, times := range count {
for range times { // range over a number repeats the loop that many times
sorted = append(sorted, age)
}
}
fmt.Println(sorted)
}
[1 3 3 3 5 5 8 9]
First, you count each age in the count array. Then you walk the array from 0 to 9 and write each age as many times as it appeared. No two items are ever compared.
Built-In Go Sorting Programs
In real code, Go sorting programs should use the standard library. It is fast, tested and short.
Program 8: slices.Sort for Numbers and Strings
package main
import (
"fmt"
"slices"
)
func main() {
numbers := []int{42, 7, 19, 3}
slices.Sort(numbers) // sorts the slice itself, small to large
fmt.Println(numbers)
names := []string{"ravi", "Asha", "meera", "Kiran"}
slices.Sort(names)
fmt.Println(names)
fmt.Println(slices.IsSorted(names)) // true if already in order
}
[3 7 19 42]
[Asha Kiran meera ravi]
true
slices.Sort sorts the slice in one line. Strings sort by byte value, so capital letters come before small ones. To ignore case, use slices.SortFunc with strings.ToLower, as in Program 10.
Program 9: Show the Top Three Scores
This everyday program sorts scores and then keeps only the best three.
package main
import (
"fmt"
"slices"
)
func main() {
scores := []int{72, 95, 60, 88, 79, 91}
// Step 1: sort from small to large.
slices.Sort(scores)
// Step 2: flip the order, so the biggest score comes first.
slices.Reverse(scores)
// Step 3: [:3] takes the first three items.
topThree := scores[:3]
fmt.Println("Top three:", topThree)
}
Top three: [95 91 88]
First, slices.Sort puts the scores from low to high. Then slices.Reverse flips them, so the best score is first. Finally, scores[:3] keeps the first three.
Program 10: Sort Descending and Case-Insensitive
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
// largeFirst compares two numbers so bigger numbers come first.
// cmp.Compare(x, y) gives -1 if x is smaller, 0 if equal and 1 if bigger.
func largeFirst(first, second int) int {
return cmp.Compare(second, first) // second goes first, so the order is flipped
}
// ignoreCase compares two words as if both were lower case.
func ignoreCase(first, second string) int {
return cmp.Compare(strings.ToLower(first), strings.ToLower(second))
}
func main() {
numbers := []int{42, 7, 19, 3}
slices.SortFunc(numbers, largeFirst) // sort using our compare function
fmt.Println(numbers)
names := []string{"ravi", "Asha", "meera", "Kiran"}
slices.SortFunc(names, ignoreCase)
fmt.Println(names)
}
[42 19 7 3]
[Asha Kiran meera ravi]
slices.SortFunc asks your function how two items compare. The function returns a negative number, zero or a positive number. Swapping first and second in cmp.Compare flips the order to descending.
Program 11: Sort Structs by a Field
package main
import (
"cmp"
"fmt"
"slices"
)
// Product is one item in a shop, with a name and a price.
type Product struct {
Name string
Price int
}
// byPrice puts cheaper products first.
func byPrice(first, second Product) int {
return cmp.Compare(first.Price, second.Price)
}
func main() {
products := []Product{{"Bag", 799}, {"Pen", 20}, {"Book", 350}, {"Lamp", 450}}
slices.SortFunc(products, byPrice)
for _, product := range products {
fmt.Println(product.Price, product.Name)
}
}
20 Pen
350 Book
450 Lamp
799 Bag
The compare function looks only at the Price field. So slices.SortFunc orders the products from cheapest to most expensive. The loop then prints each price with its name.
Program 12: Sort by Two Fields with cmp.Or
cmp.Or returns the first non-zero comparison. So it sorts by the first field, then breaks ties with the second.
package main
import (
"cmp"
"fmt"
"slices"
)
// Student holds a name and the marks scored.
type Student struct {
Name string
Marks int
}
// byMarksThenName sorts by marks high to low, and by name A to Z when marks tie.
func byMarksThenName(first, second Student) int {
return cmp.Or(
cmp.Compare(second.Marks, first.Marks), // marks high to low
cmp.Compare(first.Name, second.Name), // then name A to Z
)
}
func main() {
students := []Student{{"Ravi", 82}, {"Asha", 91}, {"Kiran", 82}, {"Meera", 91}}
slices.SortFunc(students, byMarksThenName)
fmt.Println(students)
}
[{Asha 91} {Meera 91} {Kiran 82} {Ravi 82}]
If two students have different marks, the first comparison decides. When the marks tie, it returns 0, so cmp.Or moves on to the names. That is why Asha comes before Meera.
Program 13: Stable Sort Keeps Equal Items in Order
package main
import (
"cmp"
"fmt"
"slices"
)
// Task is a job with a priority, where 1 is the most urgent.
type Task struct {
Name string
Priority int
}
// byPriority puts the most urgent tasks first.
func byPriority(first, second Task) int {
return cmp.Compare(first.Priority, second.Priority)
}
func main() {
tasks := []Task{{"email", 2}, {"deploy", 1}, {"review", 2}, {"fix bug", 1}, {"lunch", 3}}
// SortStableFunc keeps tasks with equal priority in their input order.
slices.SortStableFunc(tasks, byPriority)
fmt.Println(tasks)
}
[{deploy 1} {fix bug 1} {email 2} {review 2} {lunch 3}]
“deploy” stays before “fix bug” and “email” stays before “review”, just as in the input. A normal sort does not promise this. Use the stable version when the old order still matters.
Program 14: Sort a Map by Its Values
Maps have no order, so you copy the keys into a slice and sort that slice.
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
func main() {
sales := map[string]int{"Pune": 420, "Delhi": 980, "Goa": 150, "Mumbai": 760}
// Step 1: maps.Keys hands out each key, and slices.Collect puts them in a slice.
cities := slices.Collect(maps.Keys(sales))
// Step 2: sort the city names by their sales, high to low.
// This small function inside the call is a closure: it can read the sales map.
slices.SortFunc(cities, func(first, second string) int {
return cmp.Compare(sales[second], sales[first])
})
for _, city := range cities {
fmt.Println(city, sales[city])
}
}
Delhi 980
Mumbai 760
Pune 420
Goa 150
slices.Collect turns the key iterator into a slice. Then you sort the city names by their sales, from high to low. The function sits inside the call, because it needs to read the sales map.
Hand-Written vs Built-In Go Sorting Programs
The diagram and table below compare writing a sort yourself with using the library.

| Feature | Hand-written sort | slices.Sort and SortFunc |
|---|---|---|
| Speed on big data | Depends, often slow | Fast pdqsort |
| Bugs | Easy to make | Well tested |
| Code length | 15 to 30 lines | One line |
| Custom order | Edit the algorithm | Pass a compare function |
| Best for | Learning, interviews | Production code |
In short, practise the classic algorithms for interviews, but always use slices.Sort or slices.SortFunc at work.
Common Mistakes in Go Sorting Programs
- Off-by-one in bubble sort: the inner loop must stop at
len(numbers)-1-i, or it reads past the end. - Forgetting the result of merge sort: our merge sort returns a new slice, so assign it.
- Expecting stability:
slices.Sortandslices.SortFuncare not stable. UseSortStableFuncwhen order matters. - Case surprises: “Zoo” sorts before “apple”, because capitals come first in byte order.
- Sorting a map directly: maps cannot be sorted. Sort a slice of their keys instead.
Best Practices for Go Sorting Programs
- Use slices.Sort for basic types, since it is generic and fast.
- Call cmp.Compare inside SortFunc instead of writing your own if chains.
- Combine fields with cmp.Or, which keeps tie-breaking clear.
- Clone before sorting if the caller still needs the original order.
- Explain time and memory for any algorithm you write in an interview.
Go Sorting Programs Interview Questions and Answers
These interview questions on Go sorting programs test both algorithms and the standard sort tools. Each program is complete, with real output from Go 1.27.
Algorithm Questions on Go Sorting Programs
Q1. Which sort is best for almost sorted data?
Insertion sort. Each item moves only a few places, so it runs close to O(n). Bubble sort with an early stop is also fast here.
Q2. Why is merge sort stable but quick sort not?
Merge sort takes from the left half first when items are equal, so their order stays. Quick sort swaps items across the pivot, which can jump an item past an equal one.
Q3. What does this program print?
package main
import "fmt"
func main() {
numbers := []int{3, 1, 2}
swaps := 0
for i := 0; i < len(numbers); i++ {
for j := 0; j < len(numbers)-1-i; j++ {
if numbers[j] > numbers[j+1] {
numbers[j], numbers[j+1] = numbers[j+1], numbers[j] // swap neighbours
swaps++
}
}
}
fmt.Println(numbers, swaps)
}
[1 2 3] 2
3 swaps with 1, then 3 swaps with 2. After that, the slice is sorted, so the count is 2.
Q4. What is the worst case of quick sort, and how do libraries avoid it?
It is O(n squared), which happens when the pivot is always the smallest or largest item. Go’s slices.Sort uses pdqsort, which picks pivots carefully and falls back to heap sort if things go badly.
Go Sort Tool Questions
Q5. What does this program print?
package main
import (
"fmt"
"slices"
)
func main() {
values := []float64{2.5, -1, 3.75, 0}
slices.Sort(values)
fmt.Println(values)
// BinarySearch returns the position and found (true if the value is there).
position, found := slices.BinarySearch(values, 2.5)
fmt.Println(position, found)
}
[-1 0 2.5 3.75]
2 true
After sorting, slices.BinarySearch finds 2.5 at index 2. We cover searching fully in the next post.
Q6. What is the difference between sort.Ints and slices.Sort?
Both sort a slice of ints. sort.Ints is from the older sort package and works only for ints. slices.Sort is generic, so it works for any ordered type, and it is the modern choice.
Q7. What does this program print?
package main
import (
"fmt"
"sort"
)
// Person holds a name and an age.
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"Asha", 30}, {"Ravi", 25}, {"Meera", 35}}
// sort.Slice needs a "less" function: is the item at i smaller than the item at j?
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println(people)
}
[{Ravi 25} {Asha 30} {Meera 35}]
sort.Slice takes a “less” function with two indexes. You will see it a lot in older code, while new code prefers slices.SortFunc.
Q8. What does this program print?
package main
import (
"cmp"
"fmt"
)
func main() {
// cmp.Compare gives -1 (smaller), 0 (equal) or 1 (bigger).
fmt.Println(cmp.Compare(3, 7), cmp.Compare("b", "a"), cmp.Compare(5, 5))
// cmp.Or gives the first value that is not zero.
fmt.Println(cmp.Or(0, 0, -1, 1))
}
-1 1 0
-1
cmp.Compare returns -1, 0 or 1. cmp.Or returns the first value that is not zero, which is -1 here.
Q9. What does this program print?
package main
import (
"fmt"
"slices"
)
func main() {
words := []string{"go", "Go", "GO", "gO"}
slices.Sort(words)
fmt.Println(words)
}
[GO Go gO go]
Upper case letters have smaller byte values than lower case ones. So “GO” comes first and “go” comes last.
Q10. How do you sort a slice without changing the original?
package main
import (
"fmt"
"slices"
)
func main() {
original := []int{9, 4, 7}
// slices.Values hands out each item, and slices.Sorted builds a new sorted slice.
sorted := slices.Sorted(slices.Values(original))
fmt.Println(original, sorted)
}
[9 4 7] [4 7 9]
slices.Sorted collects the values into a new slice and sorts that. You could also call slices.Clone and then slices.Sort.
Q11. Can you sort a slice of structs by many fields?
Yes. Inside slices.SortFunc, combine comparisons with cmp.Or, from the most important field to the least. Program 12 shows this.
Q12. What is the time complexity of slices.Sort?
It is O(n log n) on average and in the worst case. It also handles already sorted or reversed data very quickly, because pdqsort spots these patterns.
Practice Task
This task is one of the most practical Go sorting programs. Write a program that sorts a list of employees by department name A to Z, and inside each department by salary from high to low. Print each employee on one line. Hint: use slices.SortFunc with cmp.Or and two cmp.Compare calls.
Official Resources
Quick Recap
- Go sorting programs can be hand-written for learning or built-in for real work.
- Bubble, selection and insertion sort are O(n squared), while merge and quick sort are O(n log n).
- A stable sort keeps equal items in their original order.
- Use
slices.Sortfor simple types andslices.SortFuncwithcmp.Comparefor custom order. - Sort maps by copying their keys into a slice first.
What’s Next?
Now that our data is in order, we can find things in it quickly. Read Go searching programs with output, with linear search, binary search and slices.BinarySearch. For more on slices, revisit our Go slice programs.


