package main
import (
"fmt"
)
func main() {
// There are a number of columns: Baimeiyingwang, Lion King, paclitaxel Dragon King, Green Wing Bat
// guessing game: input from the keyboard in any one name, number of columns determine whether to include the name of this order [to find]
// ideas
1 // define an array, Baimeiyingwang, Lion King, paclitaxel Dragon King, Bat string array Sowosky
// 2. Receives a name from the console, followed by the comparison, if found, suggesting that
// Code
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 order: first approach
//for i := 0; i < len(names); i++ {
// if heroName == names[i] {
// fmt.Printf ( "Found% v, subscript% v \ n", heroName, i)
// break
// } else if i == (len(names) - 1) {
// fmt.Printf ( "not found% v \ n", heroName)
// }
//}
// sequential search: 2 ways
index: = -1 // define a subscript, if found, the index value is changed, or has been -1
for i := 0; i < len(names); i++ {
if heroName == names[i] {
index = i // corresponding to the value of the subscript assigned to the found index
break
}
}
if index != -1 {
fmt.Printf ( "Found% v, subscript% v \ n", heroName, index)
} else {
fmt.Println ( "not found", heroName)
}
}
package main
import (
"fmt"
)
// function to find the binary
/*
Find a binary thinking: for example, we want to find the number is findVal
1. arr is an ordered array, and is from small to large
2. First find the middle subscript middle = (leftIndex + rightIndex) / 2, and let the target value and the lower intermediate compared findVal
2.1 If arr [middle]> findVal, it should be to leftIndex ---- (middle - 1)
2.2 If arr [middle] <findVal, should the middel + 1 ---- rightIndex
2.3 If arr [middle] == findVal, to find
2.4 The above logic is performed recursively 2.1 2.2 2.3
3. Think about how kind of case, it could not be found [analysis conditions for the exit recursive !!]
if leftIndex > rightIndex {
// can not find ..
return ..
}
*/
func BinaryFind (arr * [6] int, leftIndex int, rightIndex int, findVal int) {// arr * [6] int is an array of pointers received
// determines whether leftIndex greater than rightIndex
if leftIndex > rightIndex {
fmt.Println ( "not found")
return
}
// to find the middle of the subscript
middle := (leftIndex + rightIndex) / 2
if (*arr)[middle] > findVal {
// specifies the number we're looking for, should leftIndex --- middel-1
BinaryFind(arr, leftIndex, middle - 1, findVal)
} else if (*arr)[middle] < findVal {
// specifies the number we're looking for, should be in the middel + 1 --- rightIndex
BinaryFind(arr, middle + 1, rightIndex, findVal)
} else {
//found it
fmt.Printf ( "find, at index% v \ n", middle)
}
}
func main() {
arr := [6]int{1,8, 10, 89, 1000, 1234}
// a test
BinaryFind (& arr, 0, len (arr) - 1, -6) // above reception pointer, where to pass the address
}