From 9d76157e2dc91dff82ed7c8bd2598be6e418c175 Mon Sep 17 00:00:00 2001 From: cuishuang Date: Mon, 2 Dec 2024 18:12:12 +0800 Subject: [PATCH] sort: add examples for SearchStrings, SliceIsSorted Change-Id: I80b5c99bd8626be6e347f535579c864a565685db Reviewed-on: https://go-review.googlesource.com/c/go/+/632775 Reviewed-by: Ian Lance Taylor LUCI-TryBot-Result: Go LUCI Auto-Submit: Ian Lance Taylor Reviewed-by: Michael Knyszek --- src/sort/example_search_test.go | 17 +++++++++++++++++ src/sort/example_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/sort/example_search_test.go b/src/sort/example_search_test.go index eadac9a7ad..f621dfb46f 100644 --- a/src/sort/example_search_test.go +++ b/src/sort/example_search_test.go @@ -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] +} diff --git a/src/sort/example_test.go b/src/sort/example_test.go index 1f85dbcbfb..32eb73c890 100644 --- a/src/sort/example_test.go +++ b/src/sort/example_test.go @@ -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 { -- 2.48.1