本文为原创,如需转载,请注明作者和出处,谢谢!
#include <stdio.h>
int binary_search( int x, int data[], int b, int e)
{
int i;
while(b <= e)
{
i = (b + e) / 2;
if(data[i] == x) return i;
if(data[i] < x)
b = i + 1;
else
e = i - 1;
}
return - 1;
}
int binary_search_recursion( int x, int data[], int b, int e)
{
int i;
i = (b + e) / 2;
if(b > e) return - 1;
if(data[i] != x)
{
if(x < data[i])
return binary_search_recursion(x, data, 0, i - 1);
else
return binary_search_recursion(x, data, i + 1, e);
}
else
return i;
}
int main()
{
int data[] = { 1, 4, 5, 7, 9};
printf( " %d \n ", binary_search_recursion( 9, data, 0, 4));
printf( " %d \n ", binary_search( 9, data, 0, 4));
printf( " %d \n ", binary_search_recursion( 90, data, 0, 4));
printf( " %d \n ", binary_search( 89, data, 0, 4));
return 0;
}
int binary_search( int x, int data[], int b, int e)
{
int i;
while(b <= e)
{
i = (b + e) / 2;
if(data[i] == x) return i;
if(data[i] < x)
b = i + 1;
else
e = i - 1;
}
return - 1;
}
int binary_search_recursion( int x, int data[], int b, int e)
{
int i;
i = (b + e) / 2;
if(b > e) return - 1;
if(data[i] != x)
{
if(x < data[i])
return binary_search_recursion(x, data, 0, i - 1);
else
return binary_search_recursion(x, data, i + 1, e);
}
else
return i;
}
int main()
{
int data[] = { 1, 4, 5, 7, 9};
printf( " %d \n ", binary_search_recursion( 9, data, 0, 4));
printf( " %d \n ", binary_search( 9, data, 0, 4));
printf( " %d \n ", binary_search_recursion( 90, data, 0, 4));
printf( " %d \n ", binary_search( 89, data, 0, 4));
return 0;
}
本文转自银河使者博客园博客,原文链接http://www.cnblogs.com/nokiaguy/archive/2008/05/11/1192569.html如需转载请自行联系原作者
银河使者