Binary Search How to have just number argument

Light Poster
28May2009,07:21   #1
Hamed's Avatar
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.
Mentor
28May2009,12:36   #2
xpi0t0s's Avatar
How far have you got, and where are you stuck?
The code will be very similar to the code you posted.
Light Poster
28May2009,20:34   #3
Hamed's Avatar
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)
Light Poster
28May2009,20:34   #4
Hamed's Avatar
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)
Mentor
28May2009,21:25   #5
xpi0t0s's Avatar
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.
Light Poster
29May2009,00:18   #6
Hamed's Avatar
[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.
Mentor
29May2009,04:40   #7
xpi0t0s's Avatar
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);
    }
Light Poster
29May2009,07:23   #8
Hamed's Avatar
Now it need another condition I found that!!