Switch to full style
For C/C++ coders discussions and solutions
Post a reply

binary search

Sat Apr 07, 2007 2:59 am

Binary search implementation using C++
cpp code
int B(int a[],int f, int l, int t)
{
if( f > l)// 1st Base Case, return if the array is empty
{
return -1;
}
int mid = (f+l)/2;
if(a[mid] == t) // found the target
return mid;
else if(t >n)
r = B(c,0,9,n);
if( r == -1)
cout<<" Sorry !!! The Elemen Is not in our Array ... "<<endl;
else
cout<<" Your element is in the index : "<<r<<endl;
}


Another example of binary search implementation :
cpp code
#include <stdlib.h>
#include <string.h>
int bisearch(void *sorted, const void *target, int size, int esize, int
(*compare)(const void *key1, const void *key2)) {

int left,
middle,
right;

// Continue searching until left = right

left = 0;
right = size - 1;
while (left <= right) {
middle = (left + right) / 2;
switch (compare(((char *)sorted + (esize * middle)), target)) {
case -1:
// search the right of the middle index.
left = middle + 1;
break;
case 1:
// search the left of the middle index.
right = middle - 1;
break;
case 0:
return middle;
}
}
// not found
return -1;
}


Note tha the binary search order of growth is O(log2 (N) )



Re: binary search

Tue Feb 12, 2013 1:01 am

updated.

Post a reply
  Related Posts  to : binary search
 Binary search tree C++     -  
 A simple search page using Google AJAX Search API     -  
 need help for creatinb binary tree in php     -  
 Java Binary Tree     -  
 Read Binary File in C++     -  
 convert string into binary     -  
 convert to binary number     -  
 convert binary number to decimal     -  
 conversion from binary to decimal numbers as string     -  
 Naive Bayes Classification (Binary )- Supervised Learning     -  

Topic Tags

C++ Algorithms