704. 二分查找(C题解版含VS可运行源程序)
1.力扣C源码
int search(int* nums, int numsSize, int target){
int left = 0;
int right = numsSize - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
}
else if (nums[mid] > target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return -1;
}
2.题解
二分查找很简单,
适用于有序、能根据索引找到元素的集合,
对链表不是很合适。
- 初始条件:left = 0, right = length-1
- 终止:left > right
- 向左查找:right = mid-1
- 向右查找:left = mid+1
- 确定分半:mid=(right+left)/2(只保留整数位)
3.VS可运行源程序
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<limits>
#include<algorithm>
#pragma warning(disable:4996)
using namespace std;
//二分查找 很简单
const int N = 10000;
int search(int* nums, int numsSize, int target) {
int left = 0;
int right = numsSize - 1;
while (left <= right) {//注意这里是小于等于,因为有当输入只有一个元素的时候
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
}
else if (nums[mid] > target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return -1;
}
int main()
{
printf("输入数组元素个数n:");
int n;
scanf("%d", &n);
printf("输入数组元素:");
int num;
int nums[N];
for (int i = 0; i < n; i++) {
scanf("%d", &num);
nums[i] = num;
}
printf("输入目标值:");
int target;
scanf("%d", &target);
int ans = search(nums, n, target);
printf("目标值的下标为:%d", ans);
system("pause");
return 0;
}