Go sort Package

Introduction

The sort package contains functions for sorting arbitrary data.

There are several predefined sorting functions for slices of ints and floats.

Here's an example for how to sort your own data:

package main //  ww w. j  a  v a 2 s. co  m

import ("fmt" ; "sort") 

type Person struct { 
    Name string 
    Age int 
} 

type ByName []Person 

func (ps ByName) Len() int { 
    return len(ps) 
} 
func (ps ByName) Less(i, j int) bool { 
    return ps[i].Name < ps[j].Name 
} 
func (ps ByName) Swap(i, j int) { 
    ps[i], ps[j] = ps[j], ps[i] 
} 

func main() { 
    kids  := []Person{ 
        {"Jill",9}, 
        {"Jack",10}, 
    } 
    sort.Sort(ByName(kids)) 
    fmt.Println(kids) 
} 

The Sort function in sort takes a sort.Interface and sorts it.

The sort.Interface requires three methods: Len, Less, and Swap.

Len should return the length of the thing we are sorting.

For a slice, simply return len(ps).

Less is used to determine whether the item at position i is strictly less than the item at position j.

In this case, we simply compare ps[i].Name to ps[j].Name.

Swap swaps the items.

To define our own sort, we create a new type (ByName) and make it equivalent to a slice of what we want to sort. We then define the three methods.




PreviousNext

Related