Added Linear, Binary Search in Go (#94)
* Create linear-search.go * Create binary-search.go * Update README.mdpull/98/head
parent
7d9f810c06
commit
e375a9f8b0
|
@ -23,3 +23,8 @@
|
|||
1. [Linear Search](java/linear-search.java)
|
||||
2. [Binary Search](java/binary-search.java)
|
||||
3. [Jump Search](java/jump-search.java)
|
||||
|
||||
### Golang
|
||||
|
||||
1. [Linear Search](go/linear-search.go)
|
||||
2. [Binary Search](go/binary-search.go)
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var (
|
||||
arr = []int{1, 2, 4, 7, 8, 9, 12, 14, 17, 18, 20, 22, 23, 24, 26, 27, 29}
|
||||
start = 0
|
||||
end = len(arr) - 1
|
||||
elem = rand.Intn(20)
|
||||
)
|
||||
|
||||
fmt.Printf("Array: %v\nElement: %v\n", arr, elem)
|
||||
|
||||
for start <= end {
|
||||
mid := start + (end-start)/2
|
||||
if elem == arr[mid] {
|
||||
fmt.Printf("Element found at index %v", mid)
|
||||
return
|
||||
} else if elem < arr[mid] {
|
||||
end = mid - 1
|
||||
} else {
|
||||
start = mid + 1
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Element not found!\n")
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var (
|
||||
arr = rand.Perm(20)
|
||||
elem = rand.Intn(30)
|
||||
n = len(arr)
|
||||
)
|
||||
|
||||
fmt.Printf("Array: %v\nElement: %v\n", arr, elem)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
if arr[i] == elem {
|
||||
fmt.Printf("Element found at index %v", i)
|
||||
return
|
||||
}
|
||||
}
|
||||
fmt.Printf("Element not found!")
|
||||
}
|
Loading…
Reference in New Issue