普通二分法查找元素:
#include <stdio.h>
#include <stdlib.h>
int BinarySearch(int* a, int n, int pos)
{
int left = 0;
int right = n-1;
while (left <= right)
{
int mid = left+(right-left)/2;
if(pos == a[mid])
{
return mid;
}
else if(pos < a[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int ret = BinarySearch(arr, 10, 5);
printf("pos : %d\n", ret);
system("pause");
return 0;
}
显示结果:
那如果是查找数组中第一次出现的那个元素,这种方法显然是不可行。
就需要修改一小下下
#include <stdio.h>
#include <stdlib.h>
int BinarySearch(int* a, int n, int pos)
{
int left = 0;
int right = n-1;
while (left <= right)
{
int mid = left+(right-left)/2;
if(pos == a[mid])
{
while(mid-1 >= 0 && pos == a[mid-1])
{
mid = mid-1;
}
return mid;
}
else if(pos < a[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}
int main()
{
int arr1[10] = {1,2,3,4,5,6,7,8,9,10};
int arr2[13] = {1,2,3,4,5,5,5,5,6,7,8,9,10};
int ret1 = BinarySearch(arr1, 10, 5);
int ret2 = BinarySearch(arr2, 10, 5);
printf("pos1 : %d\n", ret1);
printf("pos1 : %d\n", ret2);
system("pause");
return 0;
}
显示结果:
本文出自 “Pzd流川枫” 博客,请务必保留此出处http://xujiafan.blog.51cto.com/10778767/1770159