File size: 2,017 Bytes
c14504c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
  "task_id": "task_005_binary_search",
  "difficulty": "hard",
  "description": "Fix the bugs in binary_search. It should return the index of target in a sorted array, or -1 if not found. There are multiple bugs in the boundary handling and loop condition.",
  "buggy_code": "def binary_search(arr, target):\n    low, high = 0, len(arr)\n    while low < high:\n        mid = (low + high) // 2\n        if arr[mid] == target:\n            return mid\n        elif arr[mid] < target:\n            low = mid + 1\n        else:\n            high = mid - 1\n    return -1\n",
  "solution": "def binary_search(arr, target):\n    low, high = 0, len(arr) - 1\n    while low <= high:\n        mid = (low + high) // 2\n        if arr[mid] == target:\n            return mid\n        elif arr[mid] < target:\n            low = mid + 1\n        else:\n            high = mid - 1\n    return -1\n",
  "test_descriptions": [
    "binary_search([1, 3, 5, 7, 9], 5) should return 2",
    "binary_search([1, 3, 5, 7, 9], 1) should return 0 (first element)",
    "binary_search([1, 3, 5, 7, 9], 9) should return 4 (last element)",
    "binary_search([1, 3, 5, 7, 9], 4) should return -1 (not found)",
    "binary_search([42], 42) should return 0 (single element)",
    "binary_search([], 1) should return -1 (empty array)"
  ],
  "test_code": "test_cases = [\n    (([1,3,5,7,9], 5), 2, \"find_middle\"),\n    (([1,3,5,7,9], 1), 0, \"find_first\"),\n    (([1,3,5,7,9], 9), 4, \"find_last\"),\n    (([1,3,5,7,9], 4), -1, \"not_found\"),\n    (([42], 42), 0, \"single_element\"),\n    (([], 1), -1, \"empty_array\")\n]\nfor (arr, target), exp, name in test_cases:\n    try:\n        actual = binary_search(arr, target)\n        results.append({\"test_name\": name, \"passed\": actual == exp, \"expected\": str(exp), \"actual\": str(actual), \"error\": \"\"})\n    except Exception as e:\n        results.append({\"test_name\": name, \"passed\": False, \"expected\": str(exp), \"actual\": \"\", \"error\": str(e)})",
  "max_steps": 10
}