diff --git a/main.py b/main.py new file mode 100644 index 0000000..c938048 --- /dev/null +++ b/main.py @@ -0,0 +1,56 @@ +def binary_search(arr, target): + """ + 二分查找算法 + 返回目标值在数组中的索引,如果不存在则返回 -1 + """ + left, right = 0, len(arr) - 1 + + while left <= right: + mid = left + (right - left) // 2 # 防止溢出 + + if arr[mid] == target: + return mid + elif arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return -1 + + +def test_binary_search(): + """测试二分查找函数""" + test_cases = [ + # (数组, 目标值, 期望索引) + ([1, 2, 3, 4, 5], 3, 2), + ([1, 2, 3, 4, 5], 1, 0), + ([1, 2, 3, 4, 5], 5, 4), + ([1, 2, 3, 4, 5], 0, -1), + ([1, 2, 3, 4, 5], 6, -1), + ([], 5, -1), + ([5], 5, 0), + ([5], 3, -1), + ([1, 3, 5, 7, 9], 7, 3), + ([1, 3, 5, 7, 9], 2, -1), + ] + + all_passed = True + for i, (arr, target, expected) in enumerate(test_cases): + result = binary_search(arr, target) + if result == expected: + print(f"测试用例 {i + 1} 通过: binary_search({arr}, {target}) = {result}") + else: + print(f"测试用例 {i + 1} 失败: binary_search({arr}, {target}) = {result}, 期望 {expected}") + all_passed = False + + if all_passed: + print("所有测试用例通过!") + else: + print("部分测试用例失败!") + + return all_passed + + +if __name__ == "__main__": + # 运行测试 + test_binary_search() \ No newline at end of file