Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Sorting a Slice in Golang

In Go, the standard library provides a sort package that can be used to sort slices. The sort package provides functions to sort built-in types and allows users to define sorting for custom types.

Here's a tutorial on how to sort slices in Go:

1. Sorting Slices of Built-in Types:

a. Sorting a Slice of Ints:

package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{34, 7, 23, 78, 12, 56}
	sort.Ints(nums)
	fmt.Println(nums)  // Output: [7 12 23 34 56 78]
}

b. Sorting a Slice of Strings:

package main

import (
	"fmt"
	"sort"
)

func main() {
	strs := []string{"apple", "banana", "cherry", "date"}
	sort.Strings(strs)
	fmt.Println(strs)  // Output: [apple banana cherry date]
}

c. Sorting a Slice of Floats:

package main

import (
	"fmt"
	"sort"
)

func main() {
	flts := []float64{4.5, 2.3, 7.8, 1.2}
	sort.Float64s(flts)
	fmt.Println(flts)  // Output: [1.2 2.3 4.5 7.8]
}

2. Sorting Slices of Custom Types:

If you have a slice of custom types (structs for instance), you can still sort them by defining your own type that implements the sort.Interface. This interface requires three methods: Len(), Less(i, j int) bool, and Swap(i, j int).

a. Sorting a Slice of Structs:

package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

// Define a type for the slice and make it implement sort.Interface
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func main() {
	people := []Person{
		{"Bob", 31},
		{"Alice", 25},
		{"Charlie", 29},
	}

	sort.Sort(ByAge(people))
	fmt.Println(people)
	// Output: [{Alice 25} {Charlie 29} {Bob 31}]
}

In this example, the slice of Person structs is sorted by the Age field.

3. Reverse Sorting:

If you want to sort the slice in descending order, you can use sort.Reverse() with the sort interface you defined:

sort.Sort(sort.Reverse(ByAge(people)))

Summary:

  • The sort package in Go's standard library provides a powerful way to sort slices of built-in and custom types.

  • For custom types, you'd need to implement the sort.Interface which requires defining Len(), Less(), and Swap() methods.

  • Reverse sorting is straightforward using the sort.Reverse() function.

With this knowledge, you can effectively sort slices of any type in Go!

  1. Golang sort slice example:

    • Description: An introduction to sorting slices in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          numbers := []int{4, 2, 7, 1, 9}
          sort.Ints(numbers)
          fmt.Println("Sorted Slice:", numbers)
      }
      
  2. Sorting a slice of integers in Golang:

    • Description: Sorting a slice of integers using the sort package in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          numbers := []int{4, 2, 7, 1, 9}
          sort.Ints(numbers)
          fmt.Println("Sorted Integers:", numbers)
      }
      
  3. How to use the sort package in Golang:

    • Description: A general guide on how to use the sort package in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          stringsToSort := []string{"banana", "apple", "orange", "grape"}
          sort.Strings(stringsToSort)
          fmt.Println("Sorted Strings:", stringsToSort)
      }
      
  4. Sorting a slice of strings in Golang:

    • Description: Sorting a slice of strings using the sort package in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          stringsToSort := []string{"banana", "apple", "orange", "grape"}
          sort.Strings(stringsToSort)
          fmt.Println("Sorted Strings:", stringsToSort)
      }
      
  5. Custom sorting functions in Golang:

    • Description: Implementing custom sorting functions for slices in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      type Person struct {
          Name string
          Age  int
      }
      
      type ByAge []Person
      
      func (a ByAge) Len() int           { return len(a) }
      func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
      func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
      
      func main() {
          people := []Person{
              {"Alice", 25},
              {"Bob", 30},
              {"Charlie", 22},
          }
      
          sort.Sort(ByAge(people))
          fmt.Println("Sorted People by Age:", people)
      }
      
  6. Descending order sorting in Golang slices:

    • Description: Sorting a slice in descending order using a custom sorting function in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          numbers := []int{4, 2, 7, 1, 9}
          sort.Sort(sort.Reverse(sort.IntSlice(numbers)))
          fmt.Println("Descending Order Sorted Slice:", numbers)
      }
      
  7. Sort.Slice() function in Golang:

    • Description: Using the Sort.Slice() function for custom sorting in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      func main() {
          numbers := []int{4, 2, 7, 1, 9}
          sort.Slice(numbers, func(i, j int) bool {
              return numbers[i] < numbers[j]
          })
          fmt.Println("Sorted Slice using Sort.Slice():", numbers)
      }
      
  8. Sorting slices with multiple criteria in Golang:

    • Description: Sorting slices based on multiple criteria using custom sorting functions in Golang.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      type Person struct {
          Name string
          Age  int
      }
      
      type ByAgeAndName []Person
      
      func (a ByAgeAndName) Len() int           { return len(a) }
      func (a ByAgeAndName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
      func (a ByAgeAndName) Less(i, j int) bool {
          if a[i].Age == a[j].Age {
              return a[i].Name < a[j].Name
          }
          return a[i].Age < a[j].Age
      }
      
      func main() {
          people := []Person{
              {"Alice", 25},
              {"Bob", 30},
              {"Charlie", 22},
              {"David", 25},
          }
      
          sort.Sort(ByAgeAndName(people))
          fmt.Println("Sorted People by Age and Name:", people)
      }
      
  9. Stable sorting in Golang slices:

    • Description: Achieving stable sorting in Golang slices using the Stable function from the sort package.

    • Code:

      package main
      
      import (
          "fmt"
          "sort"
      )
      
      type Person struct {
          Name string
          Age  int
      }
      
      func main() {
          people := []Person{
              {"Alice", 25},
              {"Bob", 30},
              {"Charlie", 22},
              {"David", 25},
          }
      
          sort.SliceStable(people, func(i, j int) bool {
              return people[i].Age < people[j].Age
          })
      
          fmt.Println("Stable Sorted People by Age:", people)
      }