diff --git a/algorithm/search.go b/algorithm/search.go index ad7a533..5cb7ef0 100644 --- a/algorithm/search.go +++ b/algorithm/search.go @@ -6,6 +6,17 @@ package algorithm import "github.com/duke-git/lancet/lancetconstraints" +// LinearSearch Simple linear search algorithm that iterates over all elements of an slice +// If a target is found, the index of the target is returned. Else the function return -1 +func LinearSearch[T any](slice []T, target T, comparator lancetconstraints.Comparator) int { + for i, v := range slice { + if comparator.Compare(v, target) == 0 { + return i + } + } + return -1 +} + // BinarySearch search for target within a sorted slice, recursive call itself. // If a target is found, the index of the target is returned. Else the function return -1 func BinarySearch[T any](slice []T, target T, lowIndex, highIndex int, comparator lancetconstraints.Comparator) int { diff --git a/algorithm/search_test.go b/algorithm/search_test.go index 340123c..7637ace 100644 --- a/algorithm/search_test.go +++ b/algorithm/search_test.go @@ -8,6 +8,14 @@ import ( var sortedNumbers = []int{1, 2, 3, 4, 5, 6, 7, 8} +func TestLinearSearch(t *testing.T) { + asssert := internal.NewAssert(t, "TestLinearSearch") + + comparator := &intComparator{} + asssert.Equal(4, LinearSearch(sortedNumbers, 5, comparator)) + asssert.Equal(-1, LinearSearch(sortedNumbers, 9, comparator)) +} + func TestBinarySearch(t *testing.T) { asssert := internal.NewAssert(t, "TestBinarySearch")