From 17541976f66849925280c2d162b12c947eb9c314 Mon Sep 17 00:00:00 2001 From: ale8k Date: Wed, 8 Dec 2021 21:32:25 +0000 Subject: [PATCH] Interpolation search --- .../interpolation_search.go | 37 +++++++++++++++ .../interpolation_search_test.go | 47 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 slice_searching/interpolation_search/interpolation_search.go create mode 100644 slice_searching/interpolation_search/interpolation_search_test.go diff --git a/slice_searching/interpolation_search/interpolation_search.go b/slice_searching/interpolation_search/interpolation_search.go new file mode 100644 index 0000000..2c24779 --- /dev/null +++ b/slice_searching/interpolation_search/interpolation_search.go @@ -0,0 +1,37 @@ +package interpolationsearch + +// Runs a search based on interpolation +func InterpolationSearch(param int, slice []int) int { + if param < 0 { + return -1 + } + low := 0 + mid := -1 + high := len(slice) - 1 + + for { + + if low == high || slice[low] == slice[high] { + return -1 + } + + // ((Hi - Lo)/(slice[Hi] -slice[Lo] ))*(X-slice[Lo]) + mid = low + ((high-low)/(slice[high]-slice[low]))*(param-slice[low]) + + // where − + // A = list + // Lo = Lowest index of the list + // Hi = Highest index of the list + // A[n] = Value stored at index n in the list + + if slice[mid] == param { + return mid + } else { + if slice[mid] < param { + low = mid + 1 + } else if slice[mid] > param { + high = mid - 1 + } + } + } +} diff --git a/slice_searching/interpolation_search/interpolation_search_test.go b/slice_searching/interpolation_search/interpolation_search_test.go new file mode 100644 index 0000000..e76154c --- /dev/null +++ b/slice_searching/interpolation_search/interpolation_search_test.go @@ -0,0 +1,47 @@ +package interpolationsearch + +import "testing" + +func TestInterpolationSearch(t *testing.T) { + type args struct { + param int + slice []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "it correctly finds the expected index", + args: args{ + param: 4, + slice: []int{2, 4, 6}, + }, + want: 1, + }, + { + name: "it returns -1 when out of bounds > length", + args: args{ + param: 10, + slice: []int{6, 8, 2, 4, 6}, + }, + want: -1, + }, + { + name: "it returns -1 when mid < 0", + args: args{ + param: -1, + slice: []int{6, 8, 2, 4, 6}, + }, + want: -1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := InterpolationSearch(tt.args.param, tt.args.slice); got != tt.want { + t.Errorf("InterpolationSearch() = %v, want %v", got, tt.want) + } + }) + } +}