diff --git a/searching/README.md b/searching/README.md index 0d8a364a..8ce44d1a 100644 --- a/searching/README.md +++ b/searching/README.md @@ -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) diff --git a/searching/go/binary-search.go b/searching/go/binary-search.go new file mode 100644 index 00000000..0c78157a --- /dev/null +++ b/searching/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") +} diff --git a/searching/go/linear-search.go b/searching/go/linear-search.go new file mode 100644 index 00000000..6410ed8c --- /dev/null +++ b/searching/go/linear-search.go @@ -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!") +}