二分查找
在一个长度为len数组arr[]中查找值为x的元素,所谓二分即为折半,先比较arr[mid] == x,如果等于,查找成功,如果arr[mid]
int FindValue(const int *arr, const int len, const int x)
{
int pos = -1;
if (arr == NULL || len < 1)
{
return pos;
}
int left = 0, right = len - 1;
while (left <= right)
{
int mid = (right - left + 1) / 2 + left; //(left+right)/2
if (arr[mid] == x)
{
pos = mid;
break;
}
else if (arr[mid]>x)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return pos;
}
int main()
{
int arr[] = { 12,23,34,45,56,67,78,89,100 };
int len = sizeof(arr) / sizeof(arr[0]);
int x;
cin >> x;
int pos = FindValue(arr, len, x);
cout << pos << endl;
return 0;
}
递归实现:
int SearchValue(const int* arr, int left,int right, const int x)
{
int pos = -1;
while (left <= right)
{
int mid = (right - left + 1) / 2 + left;
if (arr[mid] < x)
{
pos = SearchValue(arr, mid + 1, right, x);
}
else if (arr[mid] >x)
{
pos = SearchValue(arr, 0,right - 1, x);
}
else
{
return pos = mid;
}
}
return pos;
}
int Search(const int*arr, int len, int x)
{
if (arr == NULL || len < 1)
{
return -1;
}
else
{
return SearchValue(arr, 0, len - 1, x);
}
}