mirror of
https://github.com/golang/go
synced 2025-06-03 16:04:43 +00:00
sort: add examples for SearchStrings, SliceIsSorted
Change-Id: I80b5c99bd8626be6e347f535579c864a565685db Reviewed-on: https://go-review.googlesource.com/c/go/+/632775 Reviewed-by: Ian Lance Taylor <iant@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Auto-Submit: Ian Lance Taylor <iant@google.com> Reviewed-by: Michael Knyszek <mknyszek@google.com>
This commit is contained in:
@ -93,3 +93,20 @@ func ExampleSearchInts() {
|
||||
// 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]
|
||||
}
|
||||
|
||||
// This example demonstrates searching for string in a list sorted in ascending order.
|
||||
func ExampleSearchStrings() {
|
||||
a := []string{"apple", "banana", "cherry", "date", "fig", "grape"}
|
||||
|
||||
x := "banana"
|
||||
i := sort.SearchStrings(a, x)
|
||||
fmt.Printf("found %s at index %d in %v\n", x, i, a)
|
||||
|
||||
x = "coconut"
|
||||
i = sort.SearchStrings(a, x)
|
||||
fmt.Printf("%s not found, can be inserted at index %d in %v\n", x, i, a)
|
||||
|
||||
// Output:
|
||||
// found banana at index 1 in [apple banana cherry date fig grape]
|
||||
// coconut not found, can be inserted at index 3 in [apple banana cherry date fig grape]
|
||||
}
|
||||
|
@ -86,6 +86,34 @@ func ExampleSlice() {
|
||||
// By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
|
||||
}
|
||||
|
||||
func ExampleSliceIsSorted() {
|
||||
numbers := []int{1, 2, 3, 4, 5, 6}
|
||||
|
||||
isSortedAsc := sort.SliceIsSorted(numbers, func(i, j int) bool {
|
||||
return numbers[i] < numbers[j]
|
||||
})
|
||||
fmt.Printf("%v sorted ascending: %t\n", numbers, isSortedAsc)
|
||||
|
||||
numbersDesc := []int{6, 5, 4, 3, 2, 1}
|
||||
|
||||
isSortedDesc := sort.SliceIsSorted(numbersDesc, func(i, j int) bool {
|
||||
return numbersDesc[i] > numbersDesc[j]
|
||||
})
|
||||
fmt.Printf("%v sorted descending: %t\n", numbers, isSortedDesc)
|
||||
|
||||
unsortedNumbers := []int{1, 3, 2, 4, 5}
|
||||
|
||||
isSortedUnsorted := sort.SliceIsSorted(unsortedNumbers, func(i, j int) bool {
|
||||
return unsortedNumbers[i] < unsortedNumbers[j]
|
||||
})
|
||||
fmt.Printf("%v unsorted slice sorted: %t\n", unsortedNumbers, isSortedUnsorted)
|
||||
|
||||
// Output:
|
||||
// [1 2 3 4 5 6] sorted ascending: true
|
||||
// [1 2 3 4 5 6] sorted descending: true
|
||||
// [1 3 2 4 5] unsorted slice sorted: false
|
||||
}
|
||||
|
||||
func ExampleSliceStable() {
|
||||
|
||||
people := []struct {
|
||||
|
Reference in New Issue
Block a user