2011-08-22 06:46:59 -06:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
seq := Sequence{6, 2, -1, 44, 16}
|
|
|
|
sort.Sort(seq)
|
|
|
|
fmt.Println(seq)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Sequence []int
|
|
|
|
|
|
|
|
// Methods required by sort.Interface.
|
|
|
|
func (s Sequence) Len() int {
|
|
|
|
return len(s)
|
|
|
|
}
|
|
|
|
func (s Sequence) Less(i, j int) bool {
|
|
|
|
return s[i] < s[j]
|
|
|
|
}
|
|
|
|
func (s Sequence) Swap(i, j int) {
|
|
|
|
s[i], s[j] = s[j], s[i]
|
|
|
|
}
|
|
|
|
|
2018-11-25 20:51:08 -07:00
|
|
|
// Copy returns a copy of the Sequence.
|
|
|
|
func (s Sequence) Copy() Sequence {
|
|
|
|
copy := make(Sequence, 0, len(s))
|
|
|
|
return append(copy, s...)
|
|
|
|
}
|
|
|
|
|
2011-08-22 06:46:59 -06:00
|
|
|
// Method for printing - sorts the elements before printing.
|
|
|
|
func (s Sequence) String() string {
|
2018-11-25 20:51:08 -07:00
|
|
|
s = s.Copy() // Make a copy; don't overwrite argument.
|
2011-08-22 06:46:59 -06:00
|
|
|
sort.Sort(s)
|
|
|
|
str := "["
|
2018-11-25 20:51:08 -07:00
|
|
|
for i, elem := range s { // Loop is O(N²); will fix that in next example.
|
2011-08-22 06:46:59 -06:00
|
|
|
if i > 0 {
|
|
|
|
str += " "
|
|
|
|
}
|
|
|
|
str += fmt.Sprint(elem)
|
|
|
|
}
|
|
|
|
return str + "]"
|
|
|
|
}
|