Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolation search #62

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Searching/go/binary_search.go
Original file line number Diff line number Diff line change
@@ -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))
}
48 changes: 48 additions & 0 deletions Searching/go/interpolation_search.go
Original file line number Diff line number Diff line change
@@ -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))
}
18 changes: 18 additions & 0 deletions Searching/go/linear_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Linear Search in Golang
package main
import "fmt"

func linearSearch(target int, array []int) int {

for i:=0; i<len(array);i++{
if array[i] == target{
return i
}
}
return -1
}

func main(){
items := []int{1,2, 4, 8, 16, 32, 64}
fmt.Println(linearSearch(64, items))
}