Sort and Find 2

In Golang, we find there are two commonly used:

1) sequential search

2) binary search

Sequential search:

1) there is a series: Baimeiyingwang, Lion King, paclitaxel Dragon King, Bat Sowosky

Guessing game: Enter a name from any keyboard, the number of columns determine whether to include this name

Case presentation:
FUNC main () {

  Thinking //
  // 1. Define an array of strings
  // 2. A name received from the console, compared in turn, found to prompt corresponding information

  names: = [4] string { " Baimeiyingwang", "The Lion King", "Dragon paclitaxel", "Sowosky Bat"}
  var heroName = ""
  fmt.Println ( "Please enter the name you want to find. .. ")
  fmt.Scanln (heroName &)

  // Find the sequence: The first way
  // for I: = 0; I <len (names); I ++ {
    // == IF heroName names [I] {
      // fmt.Printf ( "find% v, subscript V% \ n-", heroName, I)
      // BREAK
    // the else IF I} == len (names) -1 {
      // fmt.Printf (" V did not find% \ n-", heroName)
    //}
  // }

  // Find sequential: 2 ways (recommended)
  index: = -1

  I for: = 0; I <len (names); I ++ {
    IF heroName == names [I] {
      index = // I corresponding to the value of the subscript assigned to find the index
      BREAK
    }
  }
  IF index = -1 {!
    fmt.Printf ( "find% v, V subscript% \ n-", heroName, index)
  } the else {
    fmt.Println ( "not found", heroName)
  }
}

 

Binary search:

Please ordered array to a binary search 1,8,10,89,1000,1234 {}, enter a number and see if the array is the presence of this number, and obtained subscript, if not prompt "no such number "[will use recursion]

Binary code looks implementation:

BinaryFind FUNC (ARR * [. 6] int, int leftIndex, rightIndex int, int findVal) {

  // determines whether leftIndex greater than rightIndex
  IF leftIndex> rightIndex {
    fmt.Println ( "not found")
    return
  }

  // to find the middle subscript
  middle: = (leftIndex + rightIndex) / 2

  IF (* arr) [Middle]> findVal {
  // specifies the number we're looking for, should be in the Middle-1 --- leftIndex
    BinaryFind (arr, leftIndex, Middle - 1, findVal)
  } the else IF (* arr) [Middle ] <findVal {
    // specifies the number we're looking for, should be + 1 --- rightIndex Middle
    BinaryFind (arr, Middle + 1, rightIndex, findVal)
  } the else {
    fmt.Printf ( "find, index is% v \ n-", Middle)
  }

}

func main() {

  arr := [6]int{1, 8, 10, 89, 1000, 1234}

  // testing a
  BinaryFind (ARR &, 0, len (ARR) -. 1, 1111)
}

Guess you like

Origin www.cnblogs.com/green-frog-2019/p/11402985.html