2008-09-15 12:48:37 -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 sort
|
|
|
|
|
2009-10-13 14:05:42 -06:00
|
|
|
type Interface interface {
|
2009-12-15 16:29:53 -07:00
|
|
|
Len() int
|
|
|
|
Less(i, j int) bool
|
|
|
|
Swap(i, j int)
|
2008-09-15 12:48:37 -06:00
|
|
|
}
|
|
|
|
|
2009-10-13 14:05:42 -06:00
|
|
|
func Sort(data Interface) {
|
2009-01-09 16:16:31 -07:00
|
|
|
for i := 1; i < data.Len(); i++ {
|
|
|
|
for j := i; j > 0 && data.Less(j, j-1); j-- {
|
2009-12-15 16:29:53 -07:00
|
|
|
data.Swap(j, j-1)
|
2008-09-15 12:48:37 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-10-13 14:05:42 -06:00
|
|
|
func IsSorted(data Interface) bool {
|
2009-12-15 16:29:53 -07:00
|
|
|
n := data.Len()
|
2009-10-13 13:37:04 -06:00
|
|
|
for i := n - 1; i > 0; i-- {
|
|
|
|
if data.Less(i, i - 1) {
|
2009-12-15 16:29:53 -07:00
|
|
|
return false
|
2008-09-15 12:48:37 -06:00
|
|
|
}
|
|
|
|
}
|
2009-12-15 16:29:53 -07:00
|
|
|
return true
|
2008-09-15 12:48:37 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// Convenience types for common cases
|
|
|
|
|
2009-01-20 15:40:40 -07:00
|
|
|
type IntArray []int
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-12-15 16:29:53 -07:00
|
|
|
func (p IntArray) Len() int { return len(p) }
|
|
|
|
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
|
|
|
|
func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
|
2011-01-19 21:07:38 -07:00
|
|
|
type Float64Array []float64
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2011-01-19 21:07:38 -07:00
|
|
|
func (p Float64Array) Len() int { return len(p) }
|
|
|
|
func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] }
|
|
|
|
func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
|
2009-01-20 15:40:40 -07:00
|
|
|
type StringArray []string
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-12-15 16:29:53 -07:00
|
|
|
func (p StringArray) Len() int { return len(p) }
|
|
|
|
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
|
|
|
|
func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
|
|
|
|
// Convenience wrappers for common cases
|
|
|
|
|
2009-12-15 16:29:53 -07:00
|
|
|
func SortInts(a []int) { Sort(IntArray(a)) }
|
2011-01-19 21:07:38 -07:00
|
|
|
func SortFloat64s(a []float64) { Sort(Float64Array(a)) }
|
2009-12-15 16:29:53 -07:00
|
|
|
func SortStrings(a []string) { Sort(StringArray(a)) }
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
|
2009-12-15 16:29:53 -07:00
|
|
|
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) }
|
2011-01-19 21:07:38 -07:00
|
|
|
func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) }
|
2009-12-15 16:29:53 -07:00
|
|
|
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) }
|