Binary Search How to have just number argument

Hamed's Avatar
Light Poster
I know this code for binary search
Code:
int search(int a[], int key, int low, int high) {
    if (high < low) {
        return NOT_FOUND; 
    }
    int mid = (low + high) / 2;
    if (key>a[mid]) {
        return searchName(a, key,low, mid-1);
    } else if (key<a[mid]) {
        return searchName(a, key,mid+1, high);
    } else {
        return EXIT_SUCCESS; 
    }
    return ERROR_SEARCH;
}
Now I want to make recursive one which just need
int search(char *dict, char *name,int length,int compChars)
and length is number element in array.
please help me.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
How far have you got, and where are you stuck?
The code will be very similar to the code you posted.
Hamed's Avatar
Light Poster
I know,
I want to change it to another function like :
int search(int a[], int key, int n) but recursive and n is number elements in array.
How can I do it.?
(I think it is clear)
Hamed's Avatar
Light Poster
I know,
I want to change it to another function like :
int search(int a[], int key, int n) but recursive and n is number elements in array.
How can I do it.?
(I think it is clear)
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yes, it's clear, but this isn't a free homework service. We'll help you if you're stuck, but we won't do your homework for you.
Hamed's Avatar
Light Poster
[PHP]
PHP Code:
int bs(int array[],int n,int key)
{
    
int mid,low=0,high=(n-1);
    
mid=n/2;
    
printf("high:%d--low:%d\n",high,low);
    if(array[
mid] == key)
    {
        return(
mid);
    }
    if(array[
mid]>key)
    { 
         
printf("mid>key\t");printf("array[mid]=%d--mid=%d\n",array[mid],mid);
        return(
bs(&(array[0]),mid,key));
    }
    if(array[
mid]<key)
    {
                      
printf("mid<key\n");printf("array[mid]=%d--mid=%d\n",array[mid],mid);
        return(
bs(&(array[mid+1]),mid,key));
    }
    if(
high low)
    {
         return(-
1);
    }
    else{
         return(-
1);
    }

This one work for all exit element but there is not condition to stop when element now exit!??
Please test it and help.I really need it before next midnight.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
You need to pass low and high in, as the first code sample you posted did. Let's say you have a 100 element array and you're at the 2nd level of recursion, say examining the elements 50-75. The bs function is going to need 50 and 75 as inputs. On the other hand, it's not going to need n, except at the top level where low=0 and high=100.

You already have a stop condition:
Code:
    if(array[mid] == key)
    {
        return(mid);
    }
Hamed's Avatar
Light Poster
Now it need another condition I found that!!