.写代码可以在整型有序数组中查找想要的数字, 找到了返回下标,找不到返回-1.(折半查找

#include<stdio.h>
#include<stdlib.h>
int search(int arr[], int n, int to_find) {
	int left = 0;
	int right = n - 1;
	int mid = (left + right) / 2;

	while (left <= right) {
		int mid = (left + right) / 2;
		if (arr[mid] < to_find) {
			left = mid + 1;
		}
		else if (arr[mid] > to_find) {
			right = mid - 1;
		}
		else {
		    return mid;
			break;
		}
	}
	return -1;

}
int main() {
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int to_find =2;
	int n = sizeof(arr) / sizeof(arr[0]);
	printf("%d\n",search(arr, n, to_find));
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44374280/article/details/89292922