dichotomy
When looking for an element in an array, it is generally traversed from beginning to end.
In order to improve efficiency, dichotomy can be used, each time it is compared with the middle value to narrow the search interval .
Solutions
Define four variables: left, the left side of the search interval, right, the right side of the search interval, mid, the middle value of the search interval, and the number we want to find toFind
In mathematics, we can express it like this: [left,right] mid=(left+right)/2
If toFind<mid, then the searched interval is updated to (left,mid)
If toFind>mid, then the searched interval is updated to (mid,right)
Until toFind=mid, we find the number we want to find
Code example
An array {1, 5, 7, 13, 24, 16} is defined here, if you need keyboard input, you can modify it yourself
#include<stdio.h>
#include<windows.h>
#pragma warning(disable:4996)
int main()
{
int toFind = 0;
int arr[] = { 1, 5, 7, 13, 24, 16 };
int left = 0;
printf("请输入要查找的数字:\n");
scanf("%d",&toFind);
int right = sizeof(arr) / sizeof(arr[0]) - 1;
while(left<=right){
int mid = (left + right) / 2;
if (toFind <arr[mid]){
right = mid - 1;
}
else if (toFind>arr[mid]){
left = mid + 1;
}
else{
printf("找到了,数组下标为:%d\n", mid);
break;
}
}
if (left > right){
printf("找不到!\n");
}
system("pause");
return 0;
}
operation result
Eat another apple~~ Come on duck~~~