diff options
author | Rob Pike <r@golang.org> | 2008-09-15 11:48:37 -0700 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2008-09-15 11:48:37 -0700 |
commit | ad9c9c42ecdae09a6b13d199199c98d8a0b1f0e9 (patch) | |
tree | 55a02d79e0f89436a4864a87892f6c9107a49da4 /doc/progs/sort.go | |
parent | e150bca19b9749bd80c658f674a09a8f0f8ec02e (diff) | |
download | golang-ad9c9c42ecdae09a6b13d199199c98d8a0b1f0e9.tar.gz |
develop interfaces through cats
sort
2,3,5
R=gri
DELTA=648 (647 added, 0 deleted, 1 changed)
OCL=15315
CL=15352
Diffstat (limited to 'doc/progs/sort.go')
-rw-r--r-- | doc/progs/sort.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/doc/progs/sort.go b/doc/progs/sort.go new file mode 100644 index 000000000..db0d8b16e --- /dev/null +++ b/doc/progs/sort.go @@ -0,0 +1,72 @@ +// 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 + +export type SortInterface interface { + len() int; + less(i, j int) bool; + swap(i, j int); +} + +export func Sort(data SortInterface) { + // Bubble sort for brevity + for i := 0; i < data.len(); i++ { + for j := i; j < data.len(); j++ { + if data.less(j, i) { + data.swap(i, j) + } + } + } +} + +export 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 + +export type IntArray struct { + data *[]int; +} + +func (p *IntArray) len() int { return len(p.data); } +func (p *IntArray) less(i, j int) bool { return p.data[i] < p.data[j]; } +func (p *IntArray) swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; } + + +export type FloatArray struct { + data *[]float; +} + +func (p *FloatArray) len() int { return len(p.data); } +func (p *FloatArray) less(i, j int) bool { return p.data[i] < p.data[j]; } +func (p *FloatArray) swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; } + + +export type StringArray struct { + data *[]string; +} + +func (p *StringArray) len() int { return len(p.data); } +func (p *StringArray) less(i, j int) bool { return p.data[i] < p.data[j]; } +func (p *StringArray) swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; } + + +// Convenience wrappers for common cases + +export func SortInts(a *[]int) { Sort(&IntArray{a}); } +export func SortFloats(a *[]float) { Sort(&FloatArray{a}); } +export func SortStrings(a *[]string) { Sort(&StringArray{a}); } + + +export func IntsAreSorted(a *[]int) bool { return IsSorted(&IntArray{a}); } +export func FloatsAreSorted(a *[]float) bool { return IsSorted(&FloatArray{a}); } +export func StringsAreSorted(a *[]string) bool { return IsSorted(&StringArray{a}); } |