在整形有序的数组中查找想要的数字,找到了返回数字下标,没找到返回-1,折半查找

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	char arr[] = { 1, 2, 3, 4, 5, 8, 9, 10 ,20};
	int to_find = 5;
	int left = 0; 
	int right = sizeof(arr) / sizeof(arr[0])-1;
	int mid = 0;
	while (left <= right) {
		mid = (left + right) / 2;
		if (arr[mid] < to_find) {
			left = mid + 1;
		}
		else if (arr[mid]>to_find) {
			right = mid - 1;
		}
		else {
			break;
		}
	}
	if (left <= right)
		printf("找到了,下标为%d", mid);
	else   printf("-1");
    system("pause");
    return 0;
 }
    

猜你喜欢

转载自blog.csdn.net/qq940051592/article/details/84774730
今日推荐