}
//查找,其中涉及指針的偏移
//查找分為順序查找
//折半查找
//兒茶查找
//分塊查找
//這裡舉的例子是二分查找
#include
#include
using namespace std;
int BinarySearch(int * Array, int n, int x)
{
int low, high, middle;
low = 0, high = n - 1;
while(low <= high)
{
middle = (low + high)/2;
if(*(Array + middle) == x)
return 1;
else
{
if(*(Array + middle) >= x)
{
high = middle - 1;
}
if(*(Array + middle) <=x)
{
low = middle + 1;
}
}
}
}
int main()
{
int Array[10] = {2, 4, 5, 13, 15, 20, 30, 35, 40, 50};
int x1, x2;
x1 = 20;
x2 = 33;
if(BinarySearch(Array, 10, x1))
printf("已經找到%d\n", x1);
else
printf("未找到%d\n", x1);
if(BinarySearch(Array, 10, x2))
printf("已經找到%d\n", x2);
else
printf("未找到%d\n", x2);
return 0;
}
上一篇