1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
|
<h1> Package sort </h1> <ul id="short-nav">
<li><code>import "sort"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul> <h2 id="pkg-overview">Overview </h2> <p>Package sort provides primitives for sorting slices and user-defined collections. </p> <h4 id="example_"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">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)
}
// ByAge implements sort.Interface for []Person based on
// the Age field.
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 < a[j].Age }
func Example() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
// There are two ways to sort a slice. First, one can define
// a set of methods for the slice type, as with ByAge, and
// call sort.Sort. In this first example we use that technique.
sort.Sort(ByAge(people))
fmt.Println(people)
// The other way is to use sort.Slice with a custom Less
// function, which can be provided as a closure. In this
// case no methods are needed. (And if they exist, they
// are ignored.) Here we re-sort in reverse order: compare
// the closure with ByAge.Less.
sort.Slice(people, func(i, j int) bool {
return people[i].Age > people[j].Age
})
fmt.Println(people)
// Output:
// [Bob: 31 John: 42 Michael: 17 Jenny: 26]
// [Michael: 17 Jenny: 26 Bob: 31 John: 42]
// [John: 42 Bob: 31 Jenny: 26 Michael: 17]
}
</pre> <h4 id="example__sortKeys"> <span class="text">Example (SortKeys)</span>
</h4> <p>ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria. </p> <p>Code:</p> <pre class="code" data-language="go">package sort_test
import (
"fmt"
"sort"
)
// A couple of type definitions to make the units clear.
type earthMass float64
type au float64
// A Planet defines the properties of a solar system object.
type Planet struct {
name string
mass earthMass
distance au
}
// By is the type of a "less" function that defines the ordering of its Planet arguments.
type By func(p1, p2 *Planet) bool
// Sort is a method on the function type, By, that sorts the argument slice according to the function.
func (by By) Sort(planets []Planet) {
ps := &planetSorter{
planets: planets,
by: by, // The Sort method's receiver is the function (closure) that defines the sort order.
}
sort.Sort(ps)
}
// planetSorter joins a By function and a slice of Planets to be sorted.
type planetSorter struct {
planets []Planet
by func(p1, p2 *Planet) bool // Closure used in the Less method.
}
// Len is part of sort.Interface.
func (s *planetSorter) Len() int {
return len(s.planets)
}
// Swap is part of sort.Interface.
func (s *planetSorter) Swap(i, j int) {
s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
}
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
func (s *planetSorter) Less(i, j int) bool {
return s.by(&s.planets[i], &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},
}
// ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.
func Example_sortKeys() {
// Closures that order the Planet structure.
name := func(p1, p2 *Planet) bool {
return p1.name < p2.name
}
mass := func(p1, p2 *Planet) bool {
return p1.mass < p2.mass
}
distance := func(p1, p2 *Planet) bool {
return p1.distance < p2.distance
}
decreasingDistance := func(p1, p2 *Planet) bool {
return distance(p2, p1)
}
// Sort the planets by the various criteria.
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)
// Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {Venus 0.815 0.7}]
// By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Earth 1 1}]
// By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars 0.107 1.5}]
// By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.7} {Mercury 0.055 0.4}]
}
</pre> <h4 id="example__sortMultiKeys"> <span class="text">Example (SortMultiKeys)</span>
</h4> <p>ExampleMultiKeys demonstrates a technique for sorting a struct type using different sets of multiple fields in the comparison. We chain together "Less" functions, each of which compares a single field. </p> <p>Code:</p> <pre class="code" data-language="go">package sort_test
import (
"fmt"
"sort"
)
// A Change is a record of source code changes, recording user, language, and delta size.
type Change struct {
user string
language string
lines int
}
type lessFunc func(p1, p2 *Change) bool
// multiSorter implements the Sort interface, sorting the changes within.
type multiSorter struct {
changes []Change
less []lessFunc
}
// Sort sorts the argument slice according to the less functions passed to OrderedBy.
func (ms *multiSorter) Sort(changes []Change) {
ms.changes = changes
sort.Sort(ms)
}
// OrderedBy returns a Sorter that sorts using the less functions, in order.
// Call its Sort method to sort the data.
func OrderedBy(less ...lessFunc) *multiSorter {
return &multiSorter{
less: less,
}
}
// Len is part of sort.Interface.
func (ms *multiSorter) Len() int {
return len(ms.changes)
}
// Swap is part of sort.Interface.
func (ms *multiSorter) Swap(i, j int) {
ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
}
// Less is part of sort.Interface. It is implemented by looping along the
// less functions until it finds a comparison that discriminates between
// the two items (one is less than the other). Note that it can call the
// less functions twice per call. We could change the functions to return
// -1, 0, 1 and reduce the number of calls for greater efficiency: an
// exercise for the reader.
func (ms *multiSorter) Less(i, j int) bool {
p, q := &ms.changes[i], &ms.changes[j]
// Try all but the last comparison.
var k int
for k = 0; k < len(ms.less)-1; k++ {
less := ms.less[k]
switch {
case less(p, q):
// p < q, so we have a decision.
return true
case less(q, p):
// p > q, so we have a decision.
return false
}
// p == q; try the next comparison.
}
// All comparisons to here said "equal", so just return whatever
// the final comparison reports.
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},
}
// ExampleMultiKeys demonstrates a technique for sorting a struct type using different
// sets of multiple fields in the comparison. We chain together "Less" functions, each of
// which compares a single field.
func Example_sortMultiKeys() {
// Closures that order the Change structure.
user := func(c1, c2 *Change) bool {
return c1.user < c2.user
}
language := func(c1, c2 *Change) bool {
return c1.language < c2.language
}
increasingLines := func(c1, c2 *Change) bool {
return c1.lines < c2.lines
}
decreasingLines := func(c1, c2 *Change) bool {
return c1.lines > c2.lines // Note: > orders downwards.
}
// Simple use: Sort by user.
OrderedBy(user).Sort(changes)
fmt.Println("By user:", changes)
// More examples.
OrderedBy(user, increasingLines).Sort(changes)
fmt.Println("By user,<lines:", changes)
OrderedBy(user, decreasingLines).Sort(changes)
fmt.Println("By user,>lines:", changes)
OrderedBy(language, increasingLines).Sort(changes)
fmt.Println("By language,<lines:", changes)
OrderedBy(language, increasingLines, user).Sort(changes)
fmt.Println("By language,<lines,user:", changes)
// Output:
// By user: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
// By user,<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}]
// By user,>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}]
// By language,<lines: [{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}]
// By language,<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}]
}
</pre> <h4 id="example__sortWrapper"> <span class="text">Example (SortWrapper)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">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] }
// ByName implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByName struct{ Organs }
func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
// ByWeight implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByWeight struct{ Organs }
func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < 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)
// Output:
// Organs by weight:
// prostate (62g)
// pancreas (131g)
// spleen (162g)
// heart (290g)
// brain (1340g)
// liver (1494g)
// Organs by name:
// brain (1340g)
// heart (290g)
// liver (1494g)
// pancreas (131g)
// prostate (62g)
// spleen (162g)
}
func printOrgans(s []*Organ) {
for _, o := range s {
fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
}
}
</pre> <h2 id="pkg-index">Index </h2> <ul id="manual-nav">
<li><a href="#Find">func Find(n int, cmp func(int) int) (i int, found bool)</a></li>
<li><a href="#Float64s">func Float64s(x []float64)</a></li>
<li><a href="#Float64sAreSorted">func Float64sAreSorted(x []float64) bool</a></li>
<li><a href="#Ints">func Ints(x []int)</a></li>
<li><a href="#IntsAreSorted">func IntsAreSorted(x []int) bool</a></li>
<li><a href="#IsSorted">func IsSorted(data Interface) bool</a></li>
<li><a href="#Search">func Search(n int, f func(int) bool) int</a></li>
<li><a href="#SearchFloat64s">func SearchFloat64s(a []float64, x float64) int</a></li>
<li><a href="#SearchInts">func SearchInts(a []int, x int) int</a></li>
<li><a href="#SearchStrings">func SearchStrings(a []string, x string) int</a></li>
<li><a href="#Slice">func Slice(x any, less func(i, j int) bool)</a></li>
<li><a href="#SliceIsSorted">func SliceIsSorted(x any, less func(i, j int) bool) bool</a></li>
<li><a href="#SliceStable">func SliceStable(x any, less func(i, j int) bool)</a></li>
<li><a href="#Sort">func Sort(data Interface)</a></li>
<li><a href="#Stable">func Stable(data Interface)</a></li>
<li><a href="#Strings">func Strings(x []string)</a></li>
<li><a href="#StringsAreSorted">func StringsAreSorted(x []string) bool</a></li>
<li><a href="#Float64Slice">type Float64Slice</a></li>
<li> <a href="#Float64Slice.Len">func (x Float64Slice) Len() int</a>
</li>
<li> <a href="#Float64Slice.Less">func (x Float64Slice) Less(i, j int) bool</a>
</li>
<li> <a href="#Float64Slice.Search">func (p Float64Slice) Search(x float64) int</a>
</li>
<li> <a href="#Float64Slice.Sort">func (x Float64Slice) Sort()</a>
</li>
<li> <a href="#Float64Slice.Swap">func (x Float64Slice) Swap(i, j int)</a>
</li>
<li><a href="#IntSlice">type IntSlice</a></li>
<li> <a href="#IntSlice.Len">func (x IntSlice) Len() int</a>
</li>
<li> <a href="#IntSlice.Less">func (x IntSlice) Less(i, j int) bool</a>
</li>
<li> <a href="#IntSlice.Search">func (p IntSlice) Search(x int) int</a>
</li>
<li> <a href="#IntSlice.Sort">func (x IntSlice) Sort()</a>
</li>
<li> <a href="#IntSlice.Swap">func (x IntSlice) Swap(i, j int)</a>
</li>
<li><a href="#Interface">type Interface</a></li>
<li> <a href="#Reverse">func Reverse(data Interface) Interface</a>
</li>
<li><a href="#StringSlice">type StringSlice</a></li>
<li> <a href="#StringSlice.Len">func (x StringSlice) Len() int</a>
</li>
<li> <a href="#StringSlice.Less">func (x StringSlice) Less(i, j int) bool</a>
</li>
<li> <a href="#StringSlice.Search">func (p StringSlice) Search(x string) int</a>
</li>
<li> <a href="#StringSlice.Sort">func (x StringSlice) Sort()</a>
</li>
<li> <a href="#StringSlice.Swap">func (x StringSlice) Swap(i, j int)</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3> <dl> <dd><a class="exampleLink" href="#example_">Package</a></dd> <dd><a class="exampleLink" href="#example_Float64s">Float64s</a></dd> <dd><a class="exampleLink" href="#example_Float64sAreSorted">Float64sAreSorted</a></dd> <dd><a class="exampleLink" href="#example_Ints">Ints</a></dd> <dd><a class="exampleLink" href="#example_IntsAreSorted">IntsAreSorted</a></dd> <dd><a class="exampleLink" href="#example_Reverse">Reverse</a></dd> <dd><a class="exampleLink" href="#example_Search">Search</a></dd> <dd><a class="exampleLink" href="#example_SearchFloat64s">SearchFloat64s</a></dd> <dd><a class="exampleLink" href="#example_SearchInts">SearchInts</a></dd> <dd><a class="exampleLink" href="#example_Search_descendingOrder">Search (DescendingOrder)</a></dd> <dd><a class="exampleLink" href="#example_Slice">Slice</a></dd> <dd><a class="exampleLink" href="#example_SliceStable">SliceStable</a></dd> <dd><a class="exampleLink" href="#example_Strings">Strings</a></dd> <dd><a class="exampleLink" href="#example__sortKeys">Package (SortKeys)</a></dd> <dd><a class="exampleLink" href="#example__sortMultiKeys">Package (SortMultiKeys)</a></dd> <dd><a class="exampleLink" href="#example__sortWrapper">Package (SortWrapper)</a></dd> </dl> </div> <h3>Package files</h3> <p> <span>search.go</span> <span>slice.go</span> <span>sort.go</span> <span>sort_impl_go121.go</span> <span>zsortfunc.go</span> <span>zsortinterface.go</span> </p> <h2 id="Find">func <span>Find</span> <span title="Added in Go 1.19">1.19</span> </h2> <pre data-language="go">func Find(n int, cmp func(int) int) (i int, found bool)</pre> <p>Find uses binary search to find and return the smallest index i in [0, n) at which cmp(i) <= 0. If there is no such index i, Find returns i = n. The found result is true if i < n and cmp(i) == 0. Find calls cmp(i) only for i in the range [0, n). </p>
<p>To permit binary search, Find requires that cmp(i) > 0 for a leading prefix of the range, cmp(i) == 0 in the middle, and cmp(i) < 0 for the final suffix of the range. (Each subrange could be empty.) The usual way to establish this condition is to interpret cmp(i) as a comparison of a desired target value t against entry i in an underlying indexed data structure x, returning <0, 0, and >0 when t < x[i], t == x[i], and t > x[i], respectively. </p>
<p>For example, to look for a particular string in a sorted, random-access list of strings: </p>
<pre data-language="go">i, found := sort.Find(x.Len(), func(i int) int {
return strings.Compare(target, x.At(i))
})
if found {
fmt.Printf("found %s at entry %d\n", target, i)
} else {
fmt.Printf("%s not found, would insert at %d", target, i)
}
</pre> <h2 id="Float64s">func <span>Float64s</span> </h2> <pre data-language="go">func Float64s(x []float64)</pre> <p>Float64s sorts a slice of float64s in increasing order. Not-a-number (NaN) values are ordered before other values. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.Sort</span>. </p> <h4 id="example_Float64s"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []float64{5.2, -1.3, 0.7, -3.8, 2.6} // unsorted
sort.Float64s(s)
fmt.Println(s)
s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0} // unsorted
sort.Float64s(s)
fmt.Println(s)
</pre> <p>Output:</p> <pre class="output" data-language="go">[-3.8 -1.3 0.7 2.6 5.2]
[NaN -Inf 0 +Inf]
</pre> <h2 id="Float64sAreSorted">func <span>Float64sAreSorted</span> </h2> <pre data-language="go">func Float64sAreSorted(x []float64) bool</pre> <p>Float64sAreSorted reports whether the slice x is sorted in increasing order, with not-a-number (NaN) values before any other values. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.IsSorted</span>. </p> <h4 id="example_Float64sAreSorted"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []float64{0.7, 1.3, 2.6, 3.8, 5.2} // sorted ascending
fmt.Println(sort.Float64sAreSorted(s))
s = []float64{5.2, 3.8, 2.6, 1.3, 0.7} // sorted descending
fmt.Println(sort.Float64sAreSorted(s))
s = []float64{5.2, 1.3, 0.7, 3.8, 2.6} // unsorted
fmt.Println(sort.Float64sAreSorted(s))
</pre> <p>Output:</p> <pre class="output" data-language="go">true
false
false
</pre> <h2 id="Ints">func <span>Ints</span> </h2> <pre data-language="go">func Ints(x []int)</pre> <p>Ints sorts a slice of ints in increasing order. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.Sort</span>. </p> <h4 id="example_Ints"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Ints(s)
fmt.Println(s)
</pre> <p>Output:</p> <pre class="output" data-language="go">[1 2 3 4 5 6]
</pre> <h2 id="IntsAreSorted">func <span>IntsAreSorted</span> </h2> <pre data-language="go">func IntsAreSorted(x []int) bool</pre> <p>IntsAreSorted reports whether the slice x is sorted in increasing order. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.IsSorted</span>. </p> <h4 id="example_IntsAreSorted"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []int{1, 2, 3, 4, 5, 6} // sorted ascending
fmt.Println(sort.IntsAreSorted(s))
s = []int{6, 5, 4, 3, 2, 1} // sorted descending
fmt.Println(sort.IntsAreSorted(s))
s = []int{3, 2, 4, 1, 5} // unsorted
fmt.Println(sort.IntsAreSorted(s))
</pre> <p>Output:</p> <pre class="output" data-language="go">true
false
false
</pre> <h2 id="IsSorted">func <span>IsSorted</span> </h2> <pre data-language="go">func IsSorted(data Interface) bool</pre> <p>IsSorted reports whether data is sorted. </p>
<p>Note: in many situations, the newer <span>slices.IsSortedFunc</span> function is more ergonomic and runs faster. </p>
<h2 id="Search">func <span>Search</span> </h2> <pre data-language="go">func Search(n int, f func(int) bool) int</pre> <p>Search uses binary search to find and return the smallest index i in [0, n) at which f(i) is true, assuming that on the range [0, n), f(i) == true implies f(i+1) == true. That is, Search requires that f is false for some (possibly empty) prefix of the input range [0, n) and then true for the (possibly empty) remainder; Search returns the first true index. If there is no such index, Search returns n. (Note that the "not found" return value is not -1 as in, for instance, strings.Index.) Search calls f(i) only for i in the range [0, n). </p>
<p>A common use of Search is to find the index i for a value x in a sorted, indexable data structure such as an array or slice. In this case, the argument f, typically a closure, captures the value to be searched for, and how the data structure is indexed and ordered. </p>
<p>For instance, given a slice data sorted in ascending order, the call Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the smallest index i such that data[i] >= 23. If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately. </p>
<p>Searching data sorted in descending order would use the <= operator instead of the >= operator. </p>
<p>To complete the example above, the following code tries to find the value x in an integer slice data sorted in ascending order: </p>
<pre data-language="go">x := 23
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i < len(data) && 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>As a more whimsical example, this program guesses your number: </p>
<pre data-language="go">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 <= %d? ", i)
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", answer)
}
</pre> <h4 id="example_Search"> <span class="text">Example</span>
</h4> <p>This example demonstrates searching a list sorted in ascending order. </p> <p>Code:</p> <pre class="code" data-language="go">a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
x := 6
i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
if i < len(a) && a[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, i, a)
} else {
fmt.Printf("%d not found in %v\n", x, a)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">found 6 at index 2 in [1 3 6 10 15 21 28 36 45 55]
</pre> <h4 id="example_Search_descendingOrder"> <span class="text">Example (DescendingOrder)</span>
</h4> <p>This example demonstrates searching a list sorted in descending order. The approach is the same as searching a list in ascending order, but with the condition inverted. </p> <p>Code:</p> <pre class="code" data-language="go">a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
x := 6
i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
if i < len(a) && a[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, i, a)
} else {
fmt.Printf("%d not found in %v\n", x, a)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]
</pre> <h2 id="SearchFloat64s">func <span>SearchFloat64s</span> </h2> <pre data-language="go">func SearchFloat64s(a []float64, x float64) int</pre> <p>SearchFloat64s searches for x in a sorted slice of float64s and returns the index as specified by <a href="#Search">Search</a>. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order. </p> <h4 id="example_SearchFloat64s"> <span class="text">Example</span>
</h4> <p>This example demonstrates searching for float64 in a list sorted in ascending order. </p> <p>Code:</p> <pre class="code" data-language="go">a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
x := 2.0
i := sort.SearchFloat64s(a, x)
fmt.Printf("found %g at index %d in %v\n", x, i, a)
x = 0.5
i = sort.SearchFloat64s(a, x)
fmt.Printf("%g not found, can be inserted at index %d in %v\n", x, i, a)
</pre> <p>Output:</p> <pre class="output" data-language="go">found 2 at index 1 in [1 2 3.3 4.6 6.1 7.2 8]
0.5 not found, can be inserted at index 0 in [1 2 3.3 4.6 6.1 7.2 8]
</pre> <h2 id="SearchInts">func <span>SearchInts</span> </h2> <pre data-language="go">func SearchInts(a []int, x int) int</pre> <p>SearchInts searches for x in a sorted slice of ints and returns the index as specified by <a href="#Search">Search</a>. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order. </p> <h4 id="example_SearchInts"> <span class="text">Example</span>
</h4> <p>This example demonstrates searching for int in a list sorted in ascending order. </p> <p>Code:</p> <pre class="code" data-language="go">a := []int{1, 2, 3, 4, 6, 7, 8}
x := 2
i := sort.SearchInts(a, x)
fmt.Printf("found %d at index %d in %v\n", x, i, a)
x = 5
i = sort.SearchInts(a, x)
fmt.Printf("%d not found, can be inserted at index %d in %v\n", x, i, a)
</pre> <p>Output:</p> <pre class="output" data-language="go">found 2 at index 1 in [1 2 3 4 6 7 8]
5 not found, can be inserted at index 4 in [1 2 3 4 6 7 8]
</pre> <h2 id="SearchStrings">func <span>SearchStrings</span> </h2> <pre data-language="go">func SearchStrings(a []string, x string) int</pre> <p>SearchStrings searches for x in a sorted slice of strings and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order. </p>
<h2 id="Slice">func <span>Slice</span> <span title="Added in Go 1.8">1.8</span> </h2> <pre data-language="go">func Slice(x any, less func(i, j int) bool)</pre> <p>Slice sorts the slice x given the provided less function. It panics if x is not a slice. </p>
<p>The sort is not guaranteed to be stable: equal elements may be reversed from their original order. For a stable sort, use <a href="#SliceStable">SliceStable</a>. </p>
<p>The less function must satisfy the same requirements as the Interface type's Less method. </p>
<p>Note: in many situations, the newer <span>slices.SortFunc</span> function is more ergonomic and runs faster. </p> <h4 id="example_Slice"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">people := []struct {
Name string
Age int
}{
{"Gopher", 7},
{"Alice", 55},
{"Vera", 24},
{"Bob", 75},
}
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age:", people)
</pre> <p>Output:</p> <pre class="output" data-language="go">By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
</pre> <h2 id="SliceIsSorted">func <span>SliceIsSorted</span> <span title="Added in Go 1.8">1.8</span> </h2> <pre data-language="go">func SliceIsSorted(x any, less func(i, j int) bool) bool</pre> <p>SliceIsSorted reports whether the slice x is sorted according to the provided less function. It panics if x is not a slice. </p>
<p>Note: in many situations, the newer <span>slices.IsSortedFunc</span> function is more ergonomic and runs faster. </p>
<h2 id="SliceStable">func <span>SliceStable</span> <span title="Added in Go 1.8">1.8</span> </h2> <pre data-language="go">func SliceStable(x any, less func(i, j int) bool)</pre> <p>SliceStable sorts the slice x using the provided less function, keeping equal elements in their original order. It panics if x is not a slice. </p>
<p>The less function must satisfy the same requirements as the Interface type's Less method. </p>
<p>Note: in many situations, the newer <span>slices.SortStableFunc</span> function is more ergonomic and runs faster. </p> <h4 id="example_SliceStable"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">people := []struct {
Name string
Age int
}{
{"Alice", 25},
{"Elizabeth", 75},
{"Alice", 75},
{"Bob", 75},
{"Alice", 75},
{"Bob", 25},
{"Colin", 25},
{"Elizabeth", 25},
}
// Sort by name, preserving original order
sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
// Sort by age preserving name order
sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age,name:", people)
</pre> <p>Output:</p> <pre class="output" data-language="go">By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]
</pre> <h2 id="Sort">func <span>Sort</span> </h2> <pre data-language="go">func Sort(data Interface)</pre> <p>Sort sorts data in ascending order as determined by the Less method. It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable. </p>
<p>Note: in many situations, the newer <span>slices.SortFunc</span> function is more ergonomic and runs faster. </p>
<h2 id="Stable">func <span>Stable</span> <span title="Added in Go 1.2">1.2</span> </h2> <pre data-language="go">func Stable(data Interface)</pre> <p>Stable sorts data in ascending order as determined by the Less method, while keeping the original order of equal elements. </p>
<p>It makes one call to data.Len to determine n, O(n*log(n)) calls to data.Less and O(n*log(n)*log(n)) calls to data.Swap. </p>
<p>Note: in many situations, the newer slices.SortStableFunc function is more ergonomic and runs faster. </p>
<h2 id="Strings">func <span>Strings</span> </h2> <pre data-language="go">func Strings(x []string)</pre> <p>Strings sorts a slice of strings in increasing order. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.Sort</span>. </p> <h4 id="example_Strings"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
sort.Strings(s)
fmt.Println(s)
</pre> <p>Output:</p> <pre class="output" data-language="go">[Alpha Bravo Delta Go Gopher Grin]
</pre> <h2 id="StringsAreSorted">func <span>StringsAreSorted</span> </h2> <pre data-language="go">func StringsAreSorted(x []string) bool</pre> <p>StringsAreSorted reports whether the slice x is sorted in increasing order. </p>
<p>Note: as of Go 1.22, this function simply calls <span>slices.IsSorted</span>. </p>
<h2 id="Float64Slice">type <span>Float64Slice</span> </h2> <p>Float64Slice implements Interface for a []float64, sorting in increasing order, with not-a-number (NaN) values ordered before other values. </p>
<pre data-language="go">type Float64Slice []float64</pre> <h3 id="Float64Slice.Len">func (Float64Slice) <span>Len</span> </h3> <pre data-language="go">func (x Float64Slice) Len() int</pre> <h3 id="Float64Slice.Less">func (Float64Slice) <span>Less</span> </h3> <pre data-language="go">func (x Float64Slice) Less(i, j int) bool</pre> <p>Less reports whether x[i] should be ordered before x[j], as required by the sort Interface. Note that floating-point comparison by itself is not a transitive relation: it does not report a consistent ordering for not-a-number (NaN) values. This implementation of Less places NaN values before any others, by using: </p>
<pre data-language="go">x[i] < x[j] || (math.IsNaN(x[i]) && !math.IsNaN(x[j]))
</pre> <h3 id="Float64Slice.Search">func (Float64Slice) <span>Search</span> </h3> <pre data-language="go">func (p Float64Slice) Search(x float64) int</pre> <p>Search returns the result of applying <a href="#SearchFloat64s">SearchFloat64s</a> to the receiver and x. </p>
<h3 id="Float64Slice.Sort">func (Float64Slice) <span>Sort</span> </h3> <pre data-language="go">func (x Float64Slice) Sort()</pre> <p>Sort is a convenience method: x.Sort() calls Sort(x). </p>
<h3 id="Float64Slice.Swap">func (Float64Slice) <span>Swap</span> </h3> <pre data-language="go">func (x Float64Slice) Swap(i, j int)</pre> <h2 id="IntSlice">type <span>IntSlice</span> </h2> <p>IntSlice attaches the methods of Interface to []int, sorting in increasing order. </p>
<pre data-language="go">type IntSlice []int</pre> <h3 id="IntSlice.Len">func (IntSlice) <span>Len</span> </h3> <pre data-language="go">func (x IntSlice) Len() int</pre> <h3 id="IntSlice.Less">func (IntSlice) <span>Less</span> </h3> <pre data-language="go">func (x IntSlice) Less(i, j int) bool</pre> <h3 id="IntSlice.Search">func (IntSlice) <span>Search</span> </h3> <pre data-language="go">func (p IntSlice) Search(x int) int</pre> <p>Search returns the result of applying <a href="#SearchInts">SearchInts</a> to the receiver and x. </p>
<h3 id="IntSlice.Sort">func (IntSlice) <span>Sort</span> </h3> <pre data-language="go">func (x IntSlice) Sort()</pre> <p>Sort is a convenience method: x.Sort() calls Sort(x). </p>
<h3 id="IntSlice.Swap">func (IntSlice) <span>Swap</span> </h3> <pre data-language="go">func (x IntSlice) Swap(i, j int)</pre> <h2 id="Interface">type <span>Interface</span> </h2> <p>An implementation of Interface can be sorted by the routines in this package. The methods refer to elements of the underlying collection by integer index. </p>
<pre data-language="go">type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with index i
// must sort before the element with index j.
//
// If both Less(i, j) and Less(j, i) are false,
// then the elements at index i and j are considered equal.
// Sort may place equal elements in any order in the final result,
// while Stable preserves the original input order of equal elements.
//
// Less must describe a transitive ordering:
// - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
// - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
//
// Note that floating-point comparison (the < operator on float32 or float64 values)
// is not a transitive ordering when not-a-number (NaN) values are involved.
// See Float64Slice.Less for a correct implementation for floating-point values.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}</pre> <h3 id="Reverse">func <span>Reverse</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func Reverse(data Interface) Interface</pre> <p>Reverse returns the reverse order for data. </p> <h4 id="example_Reverse"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">s := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Sort(sort.Reverse(sort.IntSlice(s)))
fmt.Println(s)
</pre> <p>Output:</p> <pre class="output" data-language="go">[6 5 4 3 2 1]
</pre> <h2 id="StringSlice">type <span>StringSlice</span> </h2> <p>StringSlice attaches the methods of Interface to []string, sorting in increasing order. </p>
<pre data-language="go">type StringSlice []string</pre> <h3 id="StringSlice.Len">func (StringSlice) <span>Len</span> </h3> <pre data-language="go">func (x StringSlice) Len() int</pre> <h3 id="StringSlice.Less">func (StringSlice) <span>Less</span> </h3> <pre data-language="go">func (x StringSlice) Less(i, j int) bool</pre> <h3 id="StringSlice.Search">func (StringSlice) <span>Search</span> </h3> <pre data-language="go">func (p StringSlice) Search(x string) int</pre> <p>Search returns the result of applying <a href="#SearchStrings">SearchStrings</a> to the receiver and x. </p>
<h3 id="StringSlice.Sort">func (StringSlice) <span>Sort</span> </h3> <pre data-language="go">func (x StringSlice) Sort()</pre> <p>Sort is a convenience method: x.Sort() calls Sort(x). </p>
<h3 id="StringSlice.Swap">func (StringSlice) <span>Swap</span> </h3> <pre data-language="go">func (x StringSlice) Swap(i, j int)</pre><div class="_attribution">
<p class="_attribution-p">
© Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
<a href="http://golang.org/pkg/sort/" class="_attribution-link">http://golang.org/pkg/sort/</a>
</p>
</div>
|