C 語言二分搜尋標準實作:有序陣列查找與 scanf_s 使用注意
完整程式碼 (Visual Studio 相容)
#include <stdio.h>
int binary_search(const int arr[], int len, int target) {
int left = 0, right = len - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target == arr[mid]) return mid;
else if (target > arr[mid]) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int len = sizeof(arr) / sizeof(arr[0]);
int target;
printf("請輸入查找值 (1-10): ");
scanf_s("%d", &target); // VS 安全版本
int idx = binary_search(arr, len, target);
if (idx != -1)
printf("找到 %d 於索引 %d\n", target, idx);
else
printf("不存在\n");
return 0;
}
scanf_s 與 scanf 差異
scanf_s 是 C11 附錄 K / MSVC 擴充,需傳緩衝區大小 (字串時)。整數輸入用法相同。
- 跨平台建議用標準
scanf,並自行檢查返回值。
關鍵點提醒
- 陣列必須已排序。
- 中間索引用
left + (right-left)/2 防溢位。
- 返回索引而非值,方便後續操作。
scanf_s 僅在 MSVC 預設啟用,GCC/Clang 需定義 __STDC_WANT_LIB_EXT1__。
測試
輸入: 7 -> 找到 7 於索引 6
輸入: 11 -> 不存在