The Go Programming Language

Source file doc/progs/sort.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 sort
     6	
     7	type Interface interface {
     8		Len() int
     9		Less(i, j int) bool
    10		Swap(i, j int)
    11	}
    12	
    13	func Sort(data Interface) {
    14		for i := 1; i < data.Len(); i++ {
    15			for j := i; j > 0 && data.Less(j, j-1); j-- {
    16				data.Swap(j, j-1)
    17			}
    18		}
    19	}
    20	
    21	func IsSorted(data Interface) bool {
    22		n := data.Len()
    23		for i := n - 1; i > 0; i-- {
    24			if data.Less(i, i-1) {
    25				return false
    26			}
    27		}
    28		return true
    29	}
    30	
    31	// Convenience types for common cases
    32	
    33	type IntSlice []int
    34	
    35	func (p IntSlice) Len() int           { return len(p) }
    36	func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
    37	func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
    38	
    39	type Float64Slice []float64
    40	
    41	func (p Float64Slice) Len() int           { return len(p) }
    42	func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] }
    43	func (p Float64Slice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
    44	
    45	type StringSlice []string
    46	
    47	func (p StringSlice) Len() int           { return len(p) }
    48	func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] }
    49	func (p StringSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
    50	
    51	// Convenience wrappers for common cases
    52	
    53	func SortInts(a []int)         { Sort(IntSlice(a)) }
    54	func SortFloat64s(a []float64) { Sort(Float64Slice(a)) }
    55	func SortStrings(a []string)   { Sort(StringSlice(a)) }
    56	
    57	func IntsAreSorted(a []int) bool         { return IsSorted(IntSlice(a)) }
    58	func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) }
    59	func StringsAreSorted(a []string) bool   { return IsSorted(StringSlice(a)) }

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.