How to Implement Custom Sort on Arrays in Go

1. Introduction

Custom sorting in Go is a bit more complex than sorting primitive types. Sometimes, you might need to sort complex objects like structs or arrays by a specific field or a custom condition. Fortunately, Go's sort package provides a way to implement custom sorting logic by using the sort.Interface.

Definition

The sort.Interface type in Go is an interface that requires three methods: Len(), Less(i, j int) bool, and Swap(i, j int). By implementing these methods, you can define custom sorting logic for any slice type.

2. Program Steps

1. Define a struct type to represent a collection of items that require sorting.

2. Implement the sort.Interface on the struct type.

3. Create a slice of the struct type.

4. Apply the custom sorting logic using sort.Sort.

5. Print the sorted slice to verify the results.

3. Code Program

package main

import (
	"fmt"
	"sort"
)

// Step 1: Define a struct and a corresponding slice type
type Person struct {
	Name string
	Age  int
}
type ByAge []Person

// Step 2: Implement the sort.Interface for the ByAge type
func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
	// Step 3: Create a slice of Person structs
	people := ByAge{
		{"Bob", 31},
		{"John", 42},
		{"Michael", 17},
		{"Jenny", 26},
	}

	// Step 4: Apply the custom sorting logic
	sort.Sort(people)

	// Step 5: Print the sorted slice
	fmt.Println("People sorted by age:")
	for _, p := range people {
		fmt.Printf("%s: %d\n", p.Name, p.Age)
	}
}

Output:

People sorted by age:
Michael: 17
Jenny: 26
Bob: 31
John: 42

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "sort" - Import statements for the Format package and Sort package respectively.

3. Person struct - A struct that holds a Name and an Age.

4. ByAge type - A slice of Person structs that will be sorted by age.

5. Len, Less, and Swap methods - Implementations of the sort.Interface that define how to measure the length of the collection, compare two elements, and swap two elements, respectively.

6. people slice - A slice of Person structs that we want to sort.

7. sort.Sort(people) - Calls the sort.Sort function from the sort package, which sorts the slice based on the logic provided in the Less method.

8. A for loop with range over people is used to print out each person's name and age after sorting.

9. The output demonstrates the people slice sorted in ascending order by age.


Comments