0
1
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:
cuishuang
2024-12-02 18:12:12 +08:00
committed by Gopher Robot
parent a8be834912
commit 9d76157e2d
2 changed files with 45 additions and 0 deletions

@ -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 {