1. 程式人生 > >在整形有序的陣列中查詢想要的數字,找到了返回數字下標,沒找到返回-1,折半查詢

在整形有序的陣列中查詢想要的數字,找到了返回數字下標,沒找到返回-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;
 }