diff --git a/algorithms/searching/binary_search.go b/algorithms/searching/binary_search.go new file mode 100644 index 0000000..274863f --- /dev/null +++ b/algorithms/searching/binary_search.go @@ -0,0 +1,23 @@ +package bs + +import () + +func search(sortedArray []int, el int) int { + init, end := 0, len(sortedArray)-1 + + for init <= end { + middle := ((end - init) >> 1) + init + + if sortedArray[middle] == el { + return middle + } + + if sortedArray[middle] < el { + init = middle + 1 + } else { + end = middle - 1 + } + } + + return -1 +} diff --git a/algorithms/searching/binary_search_test.go b/algorithms/searching/binary_search_test.go new file mode 100644 index 0000000..3311cf9 --- /dev/null +++ b/algorithms/searching/binary_search_test.go @@ -0,0 +1,27 @@ +package bs + +import ( + "fmt" + "testing" +) + +func TestSearch(t *testing.T) { + sorted := make([]int, 10000) + + for i := 0; i < 10000; i++ { + sorted[i] = 2 * i + } + + for i := 0; i < 10000; i++ { + index := search(sorted, 2*i) + + if index != i { + fmt.Println(index) + t.Error() + } + } + + if search(sorted, 3) != -1 { + t.Error() + } +}