1
0
mirror of https://github.com/golang/go synced 2024-10-03 03:11:21 -06:00
go/doc/progs/sort.go
Rob Pike 7839521335 Automated g4 rollback of changelist 35383.
*** Reason for rollback ***

roll back the changes to the tutorial programs (only) since they
break the automated processing used to create the tutorial.

*** Original change description ***

apply gofmt to the LGTM-marked files from 34501
that have not changed since I applied gofmt.

R=rsc
DELTA=139  (0 added, 44 deleted, 95 changed)
OCL=35670
CL=35670
2009-10-13 12:37:04 -07:00

64 lines
1.7 KiB
Go

// 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
type SortInterface interface {
Len() int;
Less(i, j int) bool;
Swap(i, j int);
}
func Sort(data SortInterface) {
for i := 1; i < data.Len(); i++ {
for j := i; j > 0 && data.Less(j, j-1); j-- {
data.Swap(j, j-1);
}
}
}
func IsSorted(data SortInterface) bool {
n := data.Len();
for i := n - 1; i > 0; i-- {
if data.Less(i, i - 1) {
return false;
}
}
return true;
}
// Convenience types for common cases
type IntArray []int
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]; }
type FloatArray []float
func (p FloatArray) Len() int { return len(p); }
func (p FloatArray) Less(i, j int) bool { return p[i] < p[j]; }
func (p FloatArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }
type StringArray []string
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]; }
// Convenience wrappers for common cases
func SortInts(a []int) { Sort(IntArray(a)); }
func SortFloats(a []float) { Sort(FloatArray(a)); }
func SortStrings(a []string) { Sort(StringArray(a)); }
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)); }
func FloatsAreSorted(a []float) bool { return IsSorted(FloatArray(a)); }
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)); }