Files
uTools-Manuals/src/docs/go/sort.html
2020-06-28 23:41:19 +08:00

500 lines
29 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<div class="container">
<h1 id="pkg-overview">package sort</h1>
<p><code>import "sort"</code>
</p><p>sort包提供了排序切片和用户自定义数据集的函数。</p>
<div class="panel-group">
<div class="panel panel-default" id="example-package">
<div class="panel-heading" onclick="document.getElementById('ex-package').style.display = document.getElementById('ex-package').style.display=='none'?'block':'none';">Example</div>
<div class="panel-collapse collapse" id="ex-package">
<div class="panel-body">
<pre>package sort_test
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
<span class="com">// ByAge implements sort.Interface for []Person based on</span>
<span class="com">// the Age field.</span>
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age &lt; a[j].Age }
func Example() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
<span class="com">// Output:</span>
<span class="com">// [Bob: 31 John: 42 Michael: 17 Jenny: 26]</span>
<span class="com">// [Michael: 17 Jenny: 26 Bob: 31 John: 42]</span>
}
</pre>
</div>
</div>
</div>
<div class="panel panel-default" id="example-package--SortKeys">
<div class="panel-heading" onclick="document.getElementById('ex-package--SortKeys').style.display = document.getElementById('ex-package--SortKeys').style.display=='none'?'block':'none';">Example (SortKeys)</div>
<div class="panel-collapse collapse" id="ex-package--SortKeys">
<div class="panel-body">
<pre>package sort_test
import (
"fmt"
"sort"
)
<span class="com">// A couple of type definitions to make the units clear.</span>
type earthMass float64
type au float64
<span class="com">// A Planet defines the properties of a solar system object.</span>
type Planet struct {
name string
mass earthMass
distance au
}
<span class="com">// By is the type of a "less" function that defines the ordering of its Planet arguments.</span>
type By func(p1, p2 *Planet) bool
<span class="com">// Sort is a method on the function type, By, that sorts the argument slice according to the function.</span>
func (by By) Sort(planets []Planet) {
ps := &amp;planetSorter{
planets: planets,
by: by, <span class="com">// The Sort method's receiver is the function (closure) that defines the sort order.</span>
}
sort.Sort(ps)
}
<span class="com">// planetSorter joins a By function and a slice of Planets to be sorted.</span>
type planetSorter struct {
planets []Planet
by func(p1, p2 *Planet) bool <span class="com">// Closure used in the Less method.</span>
}
<span class="com">// Len is part of sort.Interface.</span>
func (s *planetSorter) Len() int {
return len(s.planets)
}
<span class="com">// Swap is part of sort.Interface.</span>
func (s *planetSorter) Swap(i, j int) {
s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
}
<span class="com">// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.</span>
func (s *planetSorter) Less(i, j int) bool {
return s.by(&amp;s.planets[i], &amp;s.planets[j])
}
var planets = []Planet{
{"Mercury", 0.055, 0.4},
{"Venus", 0.815, 0.7},
{"Earth", 1.0, 1.0},
{"Mars", 0.107, 1.5},
}
<span class="com">// ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.</span>
func Example_sortKeys() {
<span class="com">// Closures that order the Planet structure.</span>
name := func(p1, p2 *Planet) bool {
return p1.name &lt; p2.name
}
mass := func(p1, p2 *Planet) bool {
return p1.mass &lt; p2.mass
}
distance := func(p1, p2 *Planet) bool {
return p1.distance &lt; p2.distance
}
decreasingDistance := func(p1, p2 *Planet) bool {
return !distance(p1, p2)
}
<span class="com">// Sort the planets by the various criteria.</span>
By(name).Sort(planets)
fmt.Println("By name:", planets)
By(mass).Sort(planets)
fmt.Println("By mass:", planets)
By(distance).Sort(planets)
fmt.Println("By distance:", planets)
By(decreasingDistance).Sort(planets)
fmt.Println("By decreasing distance:", planets)
<span class="com">// Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {Venus 0.815 0.7}]</span>
<span class="com">// By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Earth 1 1}]</span>
<span class="com">// By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars 0.107 1.5}]</span>
<span class="com">// By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.7} {Mercury 0.055 0.4}]</span>
}
</pre>
</div>
</div>
</div>
<div class="panel panel-default" id="example-package--SortMultiKeys">
<div class="panel-heading" onclick="document.getElementById('ex-package--SortMultiKeys').style.display = document.getElementById('ex-package--SortMultiKeys').style.display=='none'?'block':'none';">Example (SortMultiKeys)</div>
<div class="panel-collapse collapse" id="ex-package--SortMultiKeys">
<div class="panel-body">
<pre>package sort_test
import (
"fmt"
"sort"
)
<span class="com">// A Change is a record of source code changes, recording user, language, and delta size.</span>
type Change struct {
user string
language string
lines int
}
type lessFunc func(p1, p2 *Change) bool
<span class="com">// multiSorter implements the Sort interface, sorting the changes within.</span>
type multiSorter struct {
changes []Change
less []lessFunc
}
<span class="com">// Sort sorts the argument slice according to the less functions passed to OrderedBy.</span>
func (ms *multiSorter) Sort(changes []Change) {
ms.changes = changes
sort.Sort(ms)
}
<span class="com">// OrderedBy returns a Sorter that sorts using the less functions, in order.</span>
<span class="com">// Call its Sort method to sort the data.</span>
func OrderedBy(less ...lessFunc) *multiSorter {
return &amp;multiSorter{
less: less,
}
}
<span class="com">// Len is part of sort.Interface.</span>
func (ms *multiSorter) Len() int {
return len(ms.changes)
}
<span class="com">// Swap is part of sort.Interface.</span>
func (ms *multiSorter) Swap(i, j int) {
ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
}
<span class="com">// Less is part of sort.Interface. It is implemented by looping along the</span>
<span class="com">// less functions until it finds a comparison that is either Less or</span>
<span class="com">// !Less. Note that it can call the less functions twice per call. We</span>
<span class="com">// could change the functions to return -1, 0, 1 and reduce the</span>
<span class="com">// number of calls for greater efficiency: an exercise for the reader.</span>
func (ms *multiSorter) Less(i, j int) bool {
p, q := &amp;ms.changes[i], &amp;ms.changes[j]
<span class="com">// Try all but the last comparison.</span>
var k int
for k = 0; k &lt; len(ms.less)-1; k++ {
less := ms.less[k]
switch {
case less(p, q):
<span class="com">// p &lt; q, so we have a decision.</span>
return true
case less(q, p):
<span class="com">// p &gt; q, so we have a decision.</span>
return false
}
<span class="com">// p == q; try the next comparison.</span>
}
<span class="com">// All comparisons to here said "equal", so just return whatever</span>
<span class="com">// the final comparison reports.</span>
return ms.less[k](p, q)
}
var changes = []Change{
{"gri", "Go", 100},
{"ken", "C", 150},
{"glenda", "Go", 200},
{"rsc", "Go", 200},
{"r", "Go", 100},
{"ken", "Go", 200},
{"dmr", "C", 100},
{"r", "C", 150},
{"gri", "Smalltalk", 80},
}
<span class="com">// ExampleMultiKeys demonstrates a technique for sorting a struct type using different</span>
<span class="com">// sets of multiple fields in the comparison. We chain together "Less" functions, each of</span>
<span class="com">// which compares a single field.</span>
func Example_sortMultiKeys() {
<span class="com">// Closures that order the Change structure.</span>
user := func(c1, c2 *Change) bool {
return c1.user &lt; c2.user
}
language := func(c1, c2 *Change) bool {
return c1.language &lt; c2.language
}
increasingLines := func(c1, c2 *Change) bool {
return c1.lines &lt; c2.lines
}
decreasingLines := func(c1, c2 *Change) bool {
return c1.lines &gt; c2.lines <span class="com">// Note: &gt; orders downwards.</span>
}
<span class="com">// Simple use: Sort by user.</span>
OrderedBy(user).Sort(changes)
fmt.Println("By user:", changes)
<span class="com">// More examples.</span>
OrderedBy(user, increasingLines).Sort(changes)
fmt.Println("By user,&lt;lines:", changes)
OrderedBy(user, decreasingLines).Sort(changes)
fmt.Println("By user,&gt;lines:", changes)
OrderedBy(language, increasingLines).Sort(changes)
fmt.Println("By language,&lt;lines:", changes)
OrderedBy(language, increasingLines, user).Sort(changes)
fmt.Println("By language,&lt;lines,user:", changes)
<span class="com">// Output:</span>
<span class="com">// By user: [{dmr C 100} {glenda Go 200} {gri Smalltalk 80} {gri Go 100} {ken Go 200} {ken C 150} {r Go 100} {r C 150} {rsc Go 200}]</span>
<span class="com">// By user,&lt;lines: [{dmr C 100} {glenda Go 200} {gri Smalltalk 80} {gri Go 100} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]</span>
<span class="com">// By user,&gt;lines: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken Go 200} {ken C 150} {r C 150} {r Go 100} {rsc Go 200}]</span>
<span class="com">// By language,&lt;lines: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {ken Go 200} {glenda Go 200} {rsc Go 200} {gri Smalltalk 80}]</span>
<span class="com">// By language,&lt;lines,user: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]</span>
}
</pre>
</div>
</div>
</div>
<div class="panel panel-default" id="example-package--SortWrapper">
<div class="panel-heading" onclick="document.getElementById('ex-package--SortWrapper').style.display = document.getElementById('ex-package--SortWrapper').style.display=='none'?'block':'none';">Example (SortWrapper)</div>
<div class="panel-collapse collapse" id="ex-package--SortWrapper">
<div class="panel-body">
<pre>package sort_test
import (
"fmt"
"sort"
)
type Grams int
func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
type Organ struct {
Name string
Weight Grams
}
type Organs []*Organ
func (s Organs) Len() int { return len(s) }
func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
<span class="com">// ByName implements sort.Interface by providing Less and using the Len and</span>
<span class="com">// Swap methods of the embedded Organs value.</span>
type ByName struct{ Organs }
func (s ByName) Less(i, j int) bool { return s.Organs[i].Name &lt; s.Organs[j].Name }
<span class="com">// ByWeight implements sort.Interface by providing Less and using the Len and</span>
<span class="com">// Swap methods of the embedded Organs value.</span>
type ByWeight struct{ Organs }
func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight &lt; s.Organs[j].Weight }
func Example_sortWrapper() {
s := []*Organ{
{"brain", 1340},
{"heart", 290},
{"liver", 1494},
{"pancreas", 131},
{"prostate", 62},
{"spleen", 162},
}
sort.Sort(ByWeight{s})
fmt.Println("Organs by weight:")
printOrgans(s)
sort.Sort(ByName{s})
fmt.Println("Organs by name:")
printOrgans(s)
<span class="com">// Output:</span>
<span class="com">// Organs by weight:</span>
<span class="com">// prostate (62g)</span>
<span class="com">// pancreas (131g)</span>
<span class="com">// spleen (162g)</span>
<span class="com">// heart (290g)</span>
<span class="com">// brain (1340g)</span>
<span class="com">// liver (1494g)</span>
<span class="com">// Organs by name:</span>
<span class="com">// brain (1340g)</span>
<span class="com">// heart (290g)</span>
<span class="com">// liver (1494g)</span>
<span class="com">// pancreas (131g)</span>
<span class="com">// prostate (62g)</span>
<span class="com">// spleen (162g)</span>
}
func printOrgans(s []*Organ) {
for _, o := range s {
fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
}
}
</pre>
</div>
</div>
</div>
</div>
<h2 id="Interface">type <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#12" title="View Source">Interface</a> </h2>
<pre>type Interface interface {
<span class="com">// Len方法返回集合中的元素个数</span>
<span id="Interface.Len">Len</span>() <a href="builtin.htm#int">int</a>
<span class="com">// Less方法报告索引i的元素是否比索引j的元素小</span>
<span id="Interface.Less">Less</span>(i, j <a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a>
<span class="com">// Swap方法交换索引i和j的两个元素</span>
<span id="Interface.Swap">Swap</span>(i, j <a href="builtin.htm#int">int</a>)
}</pre>
<p>一个满足sort.Interface接口的集合类型可以被本包的函数进行排序。方法要求集合中的元素可以被整数索引。</p>
<h2 id="IntSlice">type <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#233" title="View Source">IntSlice</a> </h2>
<pre>type IntSlice []<a href="builtin.htm#int">int</a></pre>
<p>IntSlice给[]int添加方法以满足Interface接口以便排序为递增序列。</p>
<h3 id="IntSlice.Len">func (IntSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#235" title="View Source">Len</a> </h3>
<pre class="funcdecl">func (p <a href="#IntSlice">IntSlice</a>) Len() <a href="builtin.htm#int">int</a></pre>
<h3 id="IntSlice.Less">func (IntSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#236" title="View Source">Less</a> </h3>
<pre class="funcdecl">func (p <a href="#IntSlice">IntSlice</a>) Less(i, j <a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a></pre>
<h3 id="IntSlice.Swap">func (IntSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#237" title="View Source">Swap</a> </h3>
<pre class="funcdecl">func (p <a href="#IntSlice">IntSlice</a>) Swap(i, j <a href="builtin.htm#int">int</a>)</pre>
<h3 id="IntSlice.Sort">func (IntSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#240" title="View Source">Sort</a> </h3>
<pre class="funcdecl">func (p <a href="#IntSlice">IntSlice</a>) Sort()</pre>
<p>Sort等价于调用Sort(p)</p>
<h3 id="IntSlice.Search">func (IntSlice) <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#106" title="View Source">Search</a> </h3>
<pre class="funcdecl">func (p <a href="#IntSlice">IntSlice</a>) Search(x <a href="builtin.htm#int">int</a>) <a href="builtin.htm#int">int</a></pre>
<p>Search等价于调用SearchInts(p, x)</p>
<h2 id="Float64Slice">type <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#243" title="View Source">Float64Slice</a> </h2>
<pre>type Float64Slice []<a href="builtin.htm#float64">float64</a></pre>
<p>Float64Slice给[]float64添加方法以满足Interface接口以便排序为递增序列。</p>
<h3 id="Float64Slice.Len">func (Float64Slice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#245" title="View Source">Len</a> </h3>
<pre class="funcdecl">func (p <a href="#Float64Slice">Float64Slice</a>) Len() <a href="builtin.htm#int">int</a></pre>
<h3 id="Float64Slice.Less">func (Float64Slice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#246" title="View Source">Less</a> </h3>
<pre class="funcdecl">func (p <a href="#Float64Slice">Float64Slice</a>) Less(i, j <a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a></pre>
<h3 id="Float64Slice.Swap">func (Float64Slice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#247" title="View Source">Swap</a> </h3>
<pre class="funcdecl">func (p <a href="#Float64Slice">Float64Slice</a>) Swap(i, j <a href="builtin.htm#int">int</a>)</pre>
<h3 id="Float64Slice.Sort">func (Float64Slice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#255" title="View Source">Sort</a> </h3>
<pre class="funcdecl">func (p <a href="#Float64Slice">Float64Slice</a>) Sort()</pre>
<p>Sort等价于调用Sort(p)</p>
<h3 id="Float64Slice.Search">func (Float64Slice) <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#109" title="View Source">Search</a> </h3>
<pre class="funcdecl">func (p <a href="#Float64Slice">Float64Slice</a>) Search(x <a href="builtin.htm#float64">float64</a>) <a href="builtin.htm#int">int</a></pre>
<p>Search等价于调用SearchFloat64s(p, x)</p>
<h2 id="StringSlice">type <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#258" title="View Source">StringSlice</a> </h2>
<pre>type StringSlice []<a href="builtin.htm#string">string</a></pre>
<p>StringSlice给[]string添加方法以满足Interface接口以便排序为递增序列。</p>
<h3 id="StringSlice.Len">func (StringSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#260" title="View Source">Len</a> </h3>
<pre class="funcdecl">func (p <a href="#StringSlice">StringSlice</a>) Len() <a href="builtin.htm#int">int</a></pre>
<h3 id="StringSlice.Less">func (StringSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#261" title="View Source">Less</a> </h3>
<pre class="funcdecl">func (p <a href="#StringSlice">StringSlice</a>) Less(i, j <a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a></pre>
<h3 id="StringSlice.Swap">func (StringSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#262" title="View Source">Swap</a> </h3>
<pre class="funcdecl">func (p <a href="#StringSlice">StringSlice</a>) Swap(i, j <a href="builtin.htm#int">int</a>)</pre>
<h3 id="StringSlice.Sort">func (StringSlice) <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#265" title="View Source">Sort</a> </h3>
<pre class="funcdecl">func (p <a href="#StringSlice">StringSlice</a>) Sort()</pre>
<p>Sort等价于调用Sort(p)</p>
<h3 id="StringSlice.Search">func (StringSlice) <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#112" title="View Source">Search</a> </h3>
<pre class="funcdecl">func (p <a href="#StringSlice">StringSlice</a>) Search(x <a href="builtin.htm#string">string</a>) <a href="builtin.htm#int">int</a></pre>
<p>Search等价于调用SearchStrings(p, x)</p>
<h2 id="Sort">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#192" title="View Source">Sort</a> </h2>
<pre class="funcdecl">func Sort(data <a href="#Interface">Interface</a>)</pre>
<p>Sort排序data。它调用1次data.Len确定长度调用O(n*log(n))次data.Less和data.Swap。本函数不能保证排序的稳定性即不保证相等元素的相对次序不变</p>
<h2 id="Stable">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#317" title="View Source">Stable</a> </h2>
<pre class="funcdecl">func Stable(data <a href="#Interface">Interface</a>)</pre>
<p align="left">Stable排序data并保证排序的稳定性相等元素的相对次序不变。</p>
<p align="left">它调用1次data.LenO(n*log(n))次data.Less和O(n*log(n)*log(n))次data.Swap。</p>
<h2 id="IsSorted">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#220" title="View Source">IsSorted</a> </h2>
<pre class="funcdecl">func IsSorted(data <a href="#Interface">Interface</a>) <a href="builtin.htm#bool">bool</a></pre>
<p>IsSorted报告data是否已经被排序。</p>
<h2 id="Reverse">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#215" title="View Source">Reverse</a> </h2>
<pre class="funcdecl">func Reverse(data <a href="#Interface">Interface</a>) <a href="#Interface">Interface</a></pre>
<p>Reverse包装一个Interface接口并返回一个新的Interface接口对该接口排序可生成递减序列。</p>
<div class="panel-group">
<div class="panel panel-default" id="example-Reverse">
<div class="panel-heading" onclick="document.getElementById('ex-Reverse').style.display = document.getElementById('ex-Reverse').style.display=='none'?'block':'none';">Example</div>
<div class="panel-collapse collapse" id="ex-Reverse">
<div class="panel-body">
<pre>s := []int{5, 2, 6, 3, 1, 4} <span class="com">// unsorted</span>
sort.Sort(sort.Reverse(sort.IntSlice(s)))
fmt.Println(s)</pre>
<p>Output:
</p><pre>[6 5 4 3 2 1]
</pre>
</div>
</div>
</div>
</div>
<h2 id="Search">func <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#59" title="View Source">Search</a> </h2>
<pre class="funcdecl">func Search(n <a href="builtin.htm#int">int</a>, f func(<a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a>) <a href="builtin.htm#int">int</a></pre>
<p align="left">Search函数采用二分法搜索找到[0, n)区间内最小的满足f(i)==true的值i。也就是说Search函数希望f在输入位于区间[0, n)的前面某部分可以为空时返回假而在输入位于剩余至结尾的部分可以为空时返回真Search函数会返回满足f(i)==true的最小值i。如果没有该值函数会返回n。注意未找到时的返回值不是-1这一点和strings.Index等函数不同。Search函数只会用区间[0, n)内的值调用f。</p>
<p align="left">一般使用Search找到值x在插入一个有序的、可索引的数据结构时应插入的位置。这种情况下参数f通常是闭包会捕捉应搜索的值和被查询的数据集。</p>
<p align="left">例如给定一个递增顺序的切片调用Search(len(data), func(i int) bool { return data[i] &gt;= 23 })会返回data中最小的索引i满足data[i] &gt;= 23。如果调用者想要知道23是否在切片里它必须另外检查data[i] == 23。</p>
<p align="left">搜索递减顺序的数据时,应使用&lt;=运算符代替&gt;=运算符。</p>
<p align="left">下列代码尝试在一个递增顺序的整数切片中找到值x</p>
<pre>x := 23
i := sort.Search(len(data), func(i int) bool { return data[i] &gt;= x })
if i &lt; len(data) &amp;&amp; data[i] == x {
// x is present at data[i]
} else {
// x is not present in data,
// but i is the index where it would be inserted.
}</pre>
<p>一个更古怪的例子,下面的程序会猜测你持有的数字:</p>
<pre>func GuessingGame() {
var s string
fmt.Printf("Pick an integer from 0 to 100.\n")
answer := sort.Search(100, func(i int) bool {
fmt.Printf("Is your number &lt;= %d? ", i)
fmt.Scanf("%s", &amp;s)
return s != "" &amp;&amp; s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", answer)
}</pre>
<h2 id="Ints">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#270" title="View Source">Ints</a> </h2>
<pre class="funcdecl">func Ints(a []<a href="builtin.htm#int">int</a>)</pre>
<p>Ints函数将a排序为递增顺序。</p>
<div class="panel-group">
<div class="panel panel-default" id="example-Ints">
<div class="panel-heading" onclick="document.getElementById('ex-Ints').style.display = document.getElementById('ex-Ints').style.display=='none'?'block':'none';">Example</div>
<div class="panel-collapse collapse" id="ex-Ints">
<div class="panel-body">
<pre>s := []int{5, 2, 6, 3, 1, 4} <span class="com">// unsorted</span>
sort.Ints(s)
fmt.Println(s)</pre>
<p>Output:
</p><pre>[1 2 3 4 5 6]
</pre>
</div>
</div>
</div>
</div>
<h2 id="IntsAreSorted">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#279" title="View Source">IntsAreSorted</a> </h2>
<pre class="funcdecl">func IntsAreSorted(a []<a href="builtin.htm#int">int</a>) <a href="builtin.htm#bool">bool</a></pre>
<p>IntsAreSorted检查a是否已排序为递增顺序。</p>
<h2 id="SearchInts">func <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#83" title="View Source">SearchInts</a> </h2>
<pre class="funcdecl">func SearchInts(a []<a href="builtin.htm#int">int</a>, x <a href="builtin.htm#int">int</a>) <a href="builtin.htm#int">int</a></pre>
<p>SearchInts在递增顺序的a中搜索x返回x的索引。如果查找不到返回值是x应该插入a的位置以保证a的递增顺序返回值可以是len(a)。</p>
<h2 id="Float64s">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#273" title="View Source">Float64s</a> </h2>
<pre class="funcdecl">func Float64s(a []<a href="builtin.htm#float64">float64</a>)</pre>
<p>Float64s函数将a排序为递增顺序。</p>
<h2 id="Float64sAreSorted">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#282" title="View Source">Float64sAreSorted</a> </h2>
<pre class="funcdecl">func Float64sAreSorted(a []<a href="builtin.htm#float64">float64</a>) <a href="builtin.htm#bool">bool</a></pre>
<p>Float64sAreSorted检查a是否已排序为递增顺序。</p>
<h2 id="SearchFloat64s">func <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#92" title="View Source">SearchFloat64s</a> </h2>
<pre class="funcdecl">func SearchFloat64s(a []<a href="builtin.htm#float64">float64</a>, x <a href="builtin.htm#float64">float64</a>) <a href="builtin.htm#int">int</a></pre>
<p>SearchFloat64s在递增顺序的a中搜索x返回x的索引。如果查找不到返回值是x应该插入a的位置以保证a的递增顺序返回值可以是len(a)。</p>
<h2 id="Strings">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#276" title="View Source">Strings</a> </h2>
<pre class="funcdecl">func Strings(a []<a href="builtin.htm#string">string</a>)</pre>
<p>Strings函数将a排序为递增顺序。</p>
<h2 id="StringsAreSorted">func <a href="https://github.com/golang/go/blob/master/src/sort/sort.go?name=release#285" title="View Source">StringsAreSorted</a> </h2>
<pre class="funcdecl">func StringsAreSorted(a []<a href="builtin.htm#string">string</a>) <a href="builtin.htm#bool">bool</a></pre>
<p>StringsAreSorted检查a是否已排序为递增顺序。</p>
<h2 id="SearchStrings">func <a href="https://github.com/golang/go/blob/master/src/sort/search.go?name=release#101" title="View Source">SearchStrings</a> </h2>
<pre class="funcdecl">func SearchStrings(a []<a href="builtin.htm#string">string</a>, x <a href="builtin.htm#string">string</a>) <a href="builtin.htm#int">int</a></pre>
<p>SearchStrings在递增顺序的a中搜索x返回x的索引。如果查找不到返回值是x应该插入a的位置以保证a的递增顺序返回值可以是len(a)。</p>
</div>