example_search_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sort_test
  5. import (
  6. "fmt"
  7. "sort"
  8. )
  9. // This example demonstrates searching a list sorted in ascending order.
  10. func ExampleSearch() {
  11. a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
  12. x := 6
  13. i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
  14. if i < len(a) && a[i] == x {
  15. fmt.Printf("found %d at index %d in %v\n", x, i, a)
  16. } else {
  17. fmt.Printf("%d not found in %v\n", x, a)
  18. }
  19. // Output:
  20. // found 6 at index 2 in [1 3 6 10 15 21 28 36 45 55]
  21. }
  22. // This example demonstrates searching a list sorted in descending order.
  23. // The approach is the same as searching a list in ascending order,
  24. // but with the condition inverted.
  25. func ExampleSearch_descendingOrder() {
  26. a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
  27. x := 6
  28. i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
  29. if i < len(a) && a[i] == x {
  30. fmt.Printf("found %d at index %d in %v\n", x, i, a)
  31. } else {
  32. fmt.Printf("%d not found in %v\n", x, a)
  33. }
  34. // Output:
  35. // found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]
  36. }
  37. // This example demonstrates searching for float64 in a list sorted in ascending order.
  38. func ExampleSearchFloat64s() {
  39. a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
  40. x := 2.0
  41. i := sort.SearchFloat64s(a, x)
  42. fmt.Printf("found %g at index %d in %v\n", x, i, a)
  43. x = 0.5
  44. i = sort.SearchFloat64s(a, x)
  45. fmt.Printf("%g not found, can be inserted at index %d in %v\n", x, i, a)
  46. // Output:
  47. // found 2 at index 1 in [1 2 3.3 4.6 6.1 7.2 8]
  48. // 0.5 not found, can be inserted at index 0 in [1 2 3.3 4.6 6.1 7.2 8]
  49. }
  50. // This example demonstrates searching for int in a list sorted in ascending order.
  51. func ExampleSearchInts() {
  52. a := []int{1, 2, 3, 4, 6, 7, 8}
  53. x := 2
  54. i := sort.SearchInts(a, x)
  55. fmt.Printf("found %d at index %d in %v\n", x, i, a)
  56. x = 5
  57. i = sort.SearchInts(a, x)
  58. fmt.Printf("%d not found, can be inserted at index %d in %v\n", x, i, a)
  59. // Output:
  60. // found 2 at index 1 in [1 2 3 4 6 7 8]
  61. // 5 not found, can be inserted at index 4 in [1 2 3 4 6 7 8]
  62. }