資料結構›Ch7 搜尋與排序第 36 題/共 76 題
36. Binary Search、Debugging
#DS-07-036易Binary SearchDebugging
三、程式碼除錯題(共25分):請務必依序、並依題意簡要作答。
- [5%] Binary Search There is ONE BUG in the following binary search program. Please provide:
- The line number where the bug occurs, and
- The corrected solution in C.
1 #include <stdio.h>
2 // Function to perform binary search
3 // Returns the index of the target if found, otherwise returns -1
4 int binarySearch(int arr[], int size, int target) {
5 int left = 0; // Left boundary of the search
6 int right = size - 1; // Right boundary of the search
7 while (left <= right) {
8 int mid = left + (right - left) / 2; // Calculate middle index safely
9 // Check if target is at mid
10 if (arr[mid] == target) {
11 return mid; // Target found
12 }
13 if (arr[mid] < target) {
14 right = mid - 1;
15 }
16 else {
17 left = mid + 1;
18 }
19 }
20 return -1; // Target not found
21 }
22 int main() {
23 // Sorted array (binary search requires sorted data)
24 int arr[] = {2, 4, 6, 8, 10, 12, 14, 16};
25 int size = sizeof(arr) / sizeof(arr[0]);
26 int target = 10; // Value to search for
27 int result = binarySearch(arr, size, target);
28 return 0;
29 }
📄 交大115
▤完整推導請見《WH 資工筆記 · 資料結構》Ch7 搜尋與排序