Source file doc/progs/eff_sequence.go

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

View as plain text