已排序的整数数组arr为:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37]。
请用二分法查找35 和 20,分别给出它们在数组种的位置。
二分法查找(Binary Search)是一种在已排序数组中查找特定元素的搜索算法。它通过不断将数组分为两半来缩小搜索范围,直到找到所需的元素或确定元素不存在。
以下是二分法查找的基本步骤:
确定数组的最低索引(low)和最高索引(high),初始时通常是数组的第一个元素和最后一个元素。
计算中间索引(mid)作为low和high的平均值,即 mid = (low + high) / 2。
比较中间索引处的元素与目标值:
如果中间索引处的元素等于目标值,则搜索成功,返回中间索引。
如果中间索引处的元素小于目标值,则将最低索引更新为mid + 1,因为目标值必定在中间索引的右侧。
如果中间索引处的元素大于目标值,则将最高索引更新为mid - 1,因为目标值必定在中间索引的左侧。
重复步骤2和3,直到找到目标值或者最低索引大于最高索引(这意味着目标值不存在于数组中)。
#include <stdio.h> int binarySearch(int arr[], int low, int high, int target) { if (high >= low) { int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } if (arr[mid] > target) { return binarySearch(arr, low, mid - 1, target); } return binarySearch(arr, mid + 1, high, target); } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37}; int n = sizeof(arr) / sizeof(arr[0]); int target1 = 35; int target2 = 20; int result1 = binarySearch(arr, 0, n - 1, target1); int result2 = binarySearch(arr, 0, n - 1, target2); if (result1 != -1) { printf("Element %d is found at index %d\n", target1, result1); } else { printf("Element %d is not found in the array\n", target1); } if (result2 != -1) { printf("Element %d is found at index %d\n", target2, result2); } else { printf("Element %d is not found in the array\n", target2); } return 0; }