二分法查找---对有序元素集合的查找,又叫折半查找。
思路:(假设升序)将查找元素与集合中间元素比较,相等则返回;若查找元素小于集合中间元素,则在集合左半部分进行二分查找;
若查找元素大于集合中间元素,则在集合右半部分进行二分查找;(首先判断要查找的范围正确性,如果查找开始位置大于结束位置则返回未找到)
// sf.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
//二分查找 参数: 数组地址,查找开始位置,结束为止,要查找的元素
int binarysearch(int* pA, int n1, int n2, int d)
{
if (n1 > n2)
{
return -1;
}
int nMid = (n1+n2)/2;
if (d == pA[nMid])
{
return nMid;
}
else if (d < pA[nMid])
{
return binarysearch(pA, n1, nMid-1, d);
}
else
{
return binarysearch(pA, nMid+1, n2, d);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[10] = {4, 12, 17, 34, 44, 56, 78, 81, 84, 93};
int nPos = binarysearch(a, 0, 9, 77);
printf("%d\n", nPos);
nPos = binarysearch(a, 0, 9, 44);
printf("%d\n", nPos);
nPos = binarysearch(a, 0, 9, 93);
printf("%d\n", nPos);
system("pause");
return 0;
}