Added Linear, Binary Search in Go (#94)

* Create linear-search.go

* Create binary-search.go

* Update README.md
pull/98/head
Atin Bainada 2021-03-04 00:24:01 +05:30 committed by GitHub
parent 7d9f810c06
commit e375a9f8b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 64 additions and 0 deletions

View File

@ -23,3 +23,8 @@
1. [Linear Search](java/linear-search.java) 1. [Linear Search](java/linear-search.java)
2. [Binary Search](java/binary-search.java) 2. [Binary Search](java/binary-search.java)
3. [Jump Search](java/jump-search.java) 3. [Jump Search](java/jump-search.java)
### Golang
1. [Linear Search](go/linear-search.go)
2. [Binary Search](go/binary-search.go)

View File

@ -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")
}

View File

@ -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!")
}