From b17b4cbb39019ec783981e95e4720cf4ae8e0c98 Mon Sep 17 00:00:00 2001 From: dwij2812 Date: Fri, 25 Sep 2020 16:06:32 +0530 Subject: [PATCH] Added Interpolation Search --- README.md | 1 + searching/interpolationSearch.go | 65 ++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 searching/interpolationSearch.go diff --git a/README.md b/README.md index a261c2d..a2cd36b 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Algorithms * [binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm) * [linear search](https://en.wikipedia.org/wiki/Linear_search) * [jump search](https://en.wikipedia.org/wiki/Jump_search) + * [interpolation search](https://en.wikipedia.org/wiki/Interpolation_search) #### Collections diff --git a/searching/interpolationSearch.go b/searching/interpolationSearch.go new file mode 100644 index 0000000..9ff4ed9 --- /dev/null +++ b/searching/interpolationSearch.go @@ -0,0 +1,65 @@ +package main + +import "fmt" + +func InterpolationSearch(array []int, key int) int { + + min, max := array[0], array[len(array)-1] + + low, high := 0, len(array)-1 + + for { + if key < min { + return low + } + + if key > max { + return high + 1 + } + + // make a guess of the location + var guess int + if high == low { + guess = high + } else { + size := high - low + offset := int(float64(size-1) * (float64(key-min) / float64(max-min))) + guess = low + offset + } + + // maybe we found it? + if array[guess] == key { + // scan backwards for start of value range + for guess > 0 && array[guess-1] == key { + guess-- + } + return guess + } + + // if we guessed to high, guess lower or vice versa + if array[guess] > key { + high = guess - 1 + max = array[high] + } else { + low = guess + 1 + min = array[low] + } + } +} + +func main() { + searchValue := 0 + + arr := []int{1, 5, 100, 0, -100, 15, 4, 102, 30, 1000} + fmt.Println(arr) + + var index = InterpolationSearch(arr, searchValue) + + if index < 0 { + fmt.Println("Not found") + return + } else { + fmt.Println("Found at position: ", index) + return + } +}