]> Cypherpunks repositories - gostls13.git/commitdiff
sort: add examples for SearchStrings, SliceIsSorted
authorcuishuang <imcusg@gmail.com>
Mon, 2 Dec 2024 10:12:12 +0000 (18:12 +0800)
committerGopher Robot <gobot@golang.org>
Tue, 3 Dec 2024 17:07:42 +0000 (17:07 +0000)
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>
src/sort/example_search_test.go
src/sort/example_test.go

index eadac9a7adcb9780cd02852a489431d4bf0d9299..f621dfb46f80fce2f75423af88ed35bb2a124026 100644 (file)
@@ -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]
+}
index 1f85dbcbfba231e9ac7f9f525e2f070508843755..32eb73c890ded012dd47430f8e672d86ca2abaac 100644 (file)
@@ -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 {