Find the desired number in an ordered array of integers, found the return index (binary search)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main(){
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int num;
scanf("%d", &num);
int left = 0;
int right = 10;
while (left <= right){
int mid = (left + right) / 2;
if (num < arr[mid]){
right = mid - 1;
}
else if (num>arr[mid]){
left = mid + 1;
}
else{
printf("%d\n", mid);
break;
}
if (left == right){
printf("没找到!\n");
}
}
system("pause");
return 0;
}
This code is mainly understood the binary search have thought, first define the variable (left right) to indicate the current you find the boundaries of a mid to represent the intermediate value to find the range, you need to find a number of mid comparison, is less than the discard [mid, right], if greater than abandon [left, mid], until you want to find an equal number of mid. should not have to consider the situation