Question:
Given n elements arr[0:n-1] sorted, now we have to find a specific element x among these n elements. The
basic idea:
divide n elements into two halves of roughly the same number. Take arr[n/2] and compare with x. If x=arr[n/2], x is found and the algorithm terminates. If x<arr[n/2], just continue to search for x in the left half of the array arr. If x>arr[n/2], you only need to continue looking for x in the right half of the array arr.
Worst case time complexity: O(log n)
code show as below:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int Search(int x,int arr[],int n)
{
int left = 0;//左下标
int right = n-1;//右下标
while (left <= right)
{
int mid = (left + right) / 2;
if (x == arr[mid])
return mid;
if (x > arr[mid])
left = mid + 1;
else
right = mid - 1;
}
return -1;//未找到x
}
int main()
{
int num = 0;
int arr[] = {
0,1,2,3,4,5,6,7,8,9,10};
printf("请输入你想查找的数字: ");
scanf("%d", &num);
int sc = sizeof(arr)/sizeof(arr[0]);//求数组的长度(sizeof 计算字节的大小)
int temp = Search(num,arr,sc);
if (temp==-1)
printf("已给数组中找不到x\n");
else
printf("已找到x 下标是:%d\n", temp);
return 0;
}