From 026061851d032c87c64f0b6ef4c478b5f4be6e7f Mon Sep 17 00:00:00 2001 From: ZennDev1337 Date: Tue, 5 Mar 2024 10:13:43 +0100 Subject: [PATCH] update 05.03.24 --- .idea/.gitignore | 8 ++++++++ .idea/binary-search.iml | 9 +++++++++ .idea/modules.xml | 8 ++++++++ go.mod | 1 + main.go | 26 ++++++++++++++++++++++++++ main_test.go | 22 ++++++++++++++++++++++ 6 files changed, 74 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/binary-search.iml create mode 100644 .idea/modules.xml create mode 100644 go.mod create mode 100644 main.go create mode 100644 main_test.go diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/binary-search.iml b/.idea/binary-search.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/binary-search.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..01f47fe --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c92f98e --- /dev/null +++ b/go.mod @@ -0,0 +1 @@ +module binary-search diff --git a/main.go b/main.go new file mode 100644 index 0000000..7e77a23 --- /dev/null +++ b/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "errors" + "fmt" +) + +func binarySearch(nums []int, target int) (int, error) { + low := 0 + high := len(nums) - 1 + for low <= high { + mid := low + (high-low)/2 + if nums[mid] > target { + high = mid - 1 + } else if nums[mid] < target { + low = mid + 1 + } else if nums[mid] == target { + return mid, nil + } + } + return -1, errors.New("binarySearch: your target is not found in the given array") +} + +func main() { + fmt.Println("Go Fast!") +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..79de62b --- /dev/null +++ b/main_test.go @@ -0,0 +1,22 @@ +package main + +import ( + "testing" +) + +func TestBinarySearchWithWorkingTarget(t *testing.T) { + nums := []int{2, 3, 5, 7, 8} + target := 7 + resu, err := binarySearch(nums, target) + if err != nil || resu != 3 { + t.Errorf("Test failed! expected: %v, but got: %v", 3, resu) + } +} +func TestBinarySearchWithNonWorkingTarget(t *testing.T) { + nums := []int{1, 4, 5, 8, 9} + target := 2 + resu, err := binarySearch(nums, target) + if err == nil || resu != -1 { + t.Errorf("Test failed! expected: %v, but got: %v", "binarySearch: your target is not found in the given array", err) + } +}