diff --git a/src/tutorial.py b/src/tutorial.py index 54dc3d1..f847ab2 100644 --- a/src/tutorial.py +++ b/src/tutorial.py @@ -36,3 +36,22 @@ def convert_to_decimal_number(cls, num: int): for i in range(len(n)): result += int(n[i]) * (2 ** (len(n) - i - 1)) return result + + @classmethod + def binary_search(cls, values: list[int], target: int): + left = 0 + right = len(values) - 1 + answer = -1 + + while left <= right: + middle = (left + right) // 2 + if values[middle] == target: + answer = middle + right = middle - 1 + continue + if values[middle] < target: + left = middle + 1 + else: + right = middle - 1 + + return answer diff --git a/test/test_binary_search.py b/test/test_binary_search.py new file mode 100644 index 0000000..73c9a01 --- /dev/null +++ b/test/test_binary_search.py @@ -0,0 +1,46 @@ +import unittest +from src.tutorial import Tutorial + + +class TestBinarySearch(unittest.TestCase): + def test_binary_search_found_middle(self): + self.assertEqual( + Tutorial.binary_search([1, 3, 5, 7, 9], 5), + 2, + '中央の要素が見つかる' + ) + + def test_binary_search_found_first(self): + self.assertEqual( + Tutorial.binary_search([1, 3, 5, 7, 9], 1), + 0, + '先頭の要素が見つかる' + ) + + def test_binary_search_found_last(self): + self.assertEqual( + Tutorial.binary_search([1, 3, 5, 7, 9], 9), + 4, + '末尾の要素が見つかる' + ) + + def test_binary_search_not_found(self): + self.assertEqual( + Tutorial.binary_search([1, 3, 5, 7, 9], 4), + -1, + '存在しない要素は-1を返す' + ) + + def test_binary_search_duplicate_values(self): + self.assertEqual( + Tutorial.binary_search([1, 2, 2, 2, 3], 2), + 1, + '重複要素は左端のindexを返す' + ) + + def test_binary_search_empty_array(self): + self.assertEqual( + Tutorial.binary_search([], 1), + -1, + '空配列では-1を返す' + )