int a[5] = {10,20,30,40,45};
int search(int *tab, int value, int low, int high){
int med = low+(high-low)/2;
if(tab[med]>value)
return search(tab, value, low, med);
else if(tab[med]<value)
return search(tab, value, med, high);
else if(tab[med]==value)
return med;
return -1;
}
int a[5] = {10,20,30,40,45};
int search(int *tab, int value, int low, int high){
int med = low+(high-low)/2;
if(tab[med]>value)
return search(tab, value, low, med);
else if(tab[med]<value)
return search(tab, value, med, high);
else if(tab[med]==value)
return med;
return -1;
}
To copy to clipboard, switch view to plain text mode
When you call it as search(tab, 45, 0, 4) it will compare to 30, then to 40 and then to 45. It requires three steps for a 5 item array, which is more or less O(logn).
Bookmarks