From e49a01e7254249ea3f46c4a678235034de0658ad Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:28:04 +0300 Subject: [PATCH] fix(package): [algorithm] handle empty iterative searches (#399) --- algorithm/search.go | 3 +++ algorithm/search_empty_test.go | 11 +++++++++++ 2 files changed, 14 insertions(+) create mode 100644 algorithm/search_empty_test.go diff --git a/algorithm/search.go b/algorithm/search.go index da1202f..6cd3925 100644 --- a/algorithm/search.go +++ b/algorithm/search.go @@ -45,6 +45,9 @@ func BinarySearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, com // If not found return -1. // Play: https://go.dev/play/p/Anozfr8ZLH3 func BinaryIterativeSearch[T any](sortedSlice []T, target T, lowIndex, highIndex int, comparator constraints.Comparator) int { + if len(sortedSlice) == 0 { + return -1 + } startIndex := lowIndex endIndex := highIndex diff --git a/algorithm/search_empty_test.go b/algorithm/search_empty_test.go new file mode 100644 index 0000000..544c9f6 --- /dev/null +++ b/algorithm/search_empty_test.go @@ -0,0 +1,11 @@ +package algorithm + +import "testing" + +func TestBinaryIterativeSearchEmpty(t *testing.T) { + for _, source := range [][]int{nil, {}} { + if got := BinaryIterativeSearch(source, 1, 0, 0, &intComparator{}); got != -1 { + t.Errorf("got %d, want -1", got) + } + } +}