diff --git a/Searching/go/binary_search.go b/Searching/go/binary_search.go new file mode 100644 index 0000000..69847e8 --- /dev/null +++ b/Searching/go/binary_search.go @@ -0,0 +1,28 @@ +// Binary Search in Golang +package main +import "fmt" + +func binarySearch(target int, array []int) int { + + low := 0 + high := len(array) - 1 + + for low <= high{ + middle:= (high-low) / 2 + low + + if array[middle] == target{ + return middle + } + if array[middle] < target { + low = middle + 1 + }else{ + high = middle - 1 + } + } + return -1 +} + +func main(){ + items := []int{1,2, 4, 8, 16, 32, 64} + fmt.Println(binarySearch(64, items)) +} \ No newline at end of file diff --git a/Searching/go/interpolation_search.go b/Searching/go/interpolation_search.go new file mode 100644 index 0000000..cf9497d --- /dev/null +++ b/Searching/go/interpolation_search.go @@ -0,0 +1,48 @@ +package main +import "fmt" + +func interpolationSearch(target int, array []int) int { + + min, max := array[0], array[len(array)-1] + + low, high := 0, len(array)-1 + + for { + if target < min { + return low + } + + if target > max { + return high + 1 + } + + var guess int + if high == low { + guess = high + } else { + size := high - low + offset := int(float64(size-1) * (float64(target-min) / float64(max-min))) + guess = low + offset + } + + if array[guess] == target { + for guess > 0 && array[guess-1] == target { + guess-- + } + return guess + } + + if array[guess] > target { + high = guess - 1 + max = array[high] + } else { + low = guess + 1 + min = array[low] + } + } +} + +func main(){ + items := []int{1,2, 4, 8, 16, 32, 64} + fmt.Println(interpolationSearch(64, items)) +} \ No newline at end of file diff --git a/Searching/go/linear_search.go b/Searching/go/linear_search.go new file mode 100644 index 0000000..e7d46b4 --- /dev/null +++ b/Searching/go/linear_search.go @@ -0,0 +1,18 @@ +// Linear Search in Golang +package main +import "fmt" + +func linearSearch(target int, array []int) int { + + for i:=0; i