github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/doc/progs/eff_sequence.go (about)

     1  // cmpout
     2  
     3  // Copyright 2009 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"sort"
    12  )
    13  
    14  func main() {
    15  	seq := Sequence{6, 2, -1, 44, 16}
    16  	sort.Sort(seq)
    17  	fmt.Println(seq)
    18  }
    19  
    20  type Sequence []int
    21  
    22  // Methods required by sort.Interface.
    23  func (s Sequence) Len() int {
    24  	return len(s)
    25  }
    26  func (s Sequence) Less(i, j int) bool {
    27  	return s[i] < s[j]
    28  }
    29  func (s Sequence) Swap(i, j int) {
    30  	s[i], s[j] = s[j], s[i]
    31  }
    32  
    33  // Method for printing - sorts the elements before printing.
    34  func (s Sequence) String() string {
    35  	sort.Sort(s)
    36  	str := "["
    37  	for i, elem := range s {
    38  		if i > 0 {
    39  			str += " "
    40  		}
    41  		str += fmt.Sprint(elem)
    42  	}
    43  	return str + "]"
    44  }