Skip to content

Commit

Permalink
Interpolation search
Browse files Browse the repository at this point in the history
  • Loading branch information
ale8k committed Dec 8, 2021
1 parent 9100bf2 commit 1754197
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
37 changes: 37 additions & 0 deletions slice_searching/interpolation_search/interpolation_search.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
}
47 changes: 47 additions & 0 deletions slice_searching/interpolation_search/interpolation_search_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit 1754197

Please sign in to comment.