Home > php教程 > PHP开发 > Binary search C language implementation

Binary search C language implementation

高洛峰
Release: 2016-12-19 16:21:38
Original
1448 people have browsed it

Binary search:

a is the array to be searched. The prerequisite for binary search is that the a data is sorted. key is the variable to be searched, and n is the length of array a.

int binary( int *a, int key, int n )
{
int left = 0, right = n - 1, mid = 0;
mid = ( left + right ) / 2;
while( left < right && a[mid] != key )
{
if( a[mid] < key )
left = mid + 1;
key ) else if( a[mid] > key ) right = mid - 1;
mid = ( left + right ) / 2;
}
if( a[mid] == key ) return mid;
return -1;
}

Call:

Find the lower part of array b in array a Target position (when the data in b does not exist in a, -1 is used instead).

int main()

{
int a[] = {1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677};
int b[ ] = { 677, 1, 7, 11, 67 };
int i;
for( i=0; i
{
printf( "%dn", binary( a, b[i], sizeof(a)/ sizeof(a[0])));
}
return 0;
}



For more articles related to binary search C language implementation, please pay attention to PHP Chinese website

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template