2009年12月16日 星期三

binary search

inline int binarysearch(int a[], int n, int key){

int high=n-1;
int low=0;
int mid;
int index=-1;
if(key==a[high] )
return high;
if(key==a[low])
return low;

while((high!=(n-1) )&& (low !=0)){

mid=(low+high)/2;
if(a[mid]==key){
index=mid;
goto found;
}else if(a[mid] < key){

high=n-1;
low=mid+1;
}else if(a[mid] > key){

high=mid-1;
low=0;
}


}

found:

return index;

}
referenc:

http://program-lover.blogspot.com/2008/08/binary-search.html

沒有留言: