Thread: recursive search function

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    808

    recursive search function

    i have written a simple recursive search function to search an array for a given number.

    Code:
    int SearchArray( int iNum[], int iStart, int iEnd, int iSearchNum )
    {
        //break out clauses
        if ( iNum[ iStart ] == iSearchNum )
        {
            return iStart;
        }
        else if ( iNum[ iEnd ] == iSearchNum )
        {
            return iEnd;
        }
        //else if ( sizeof( iNum ) / sizeof( int ) <= 2 ) THIS DOESNT WORK!!
        else if ( iEnd -iStart <= 1 )
        {
            //number not in array so inform user and return 0
            printf("number not found!!\n");
            return 0;
        }
    
        //find the middle of the current array
        int iMid = ( iEnd - iStart ) / 2 + iStart; //if first itteration i start will be 0 so same as iend / 2 ie middle of the whole array
    
        //make sure imid isnt equal to searchnum
        if ( iNum[ iMid ] == iSearchNum )
        {
            return iMid;
        }
        //if imid is less than isearchnum send second half of the current array back round
        else if ( iNum[ iMid ] < iSearchNum )
        {
            return SearchArray( iNum, iMid, iEnd, iSearchNum );
        }
        //imid is greater than isearchnum so send first half of the current array back round
        else
        {
            return SearchArray( iNum, iStart, iMid, iSearchNum );
        }
    }
    as you can see from the comment on line 12 my first attempt caused warning: ‘sizeof’ on array function parameter ‘iNum’ will return size of ‘int *’ [-Wsizeof-array-argument]| is there a better way round this.

    Also would it be better to pass the index via a pointer rather than return it as an int

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    Post a whole program so we don't have to write the rest to run it.
    It also allows us to see how you are calling the function.

    Again, it is generally considered idiotic to preface variables with type designators.

    Anyway, iNum is just a pointer. It's sizeof is the size of a pointer, not of an array. Normally we would declare it as int *num, not int num[] to reflect this fact.

    At any rate, you don't need the array's size since you have the start and end indices. The initial end index should be one-past-the-end (i.e., the size of the array).

    Do not print anything in the function. The user of the function should decide whether and what to print. Instead, return -1 if the value is not found.

    Your function is a little over-complicated. You certainly don't need to check the start and end positions.

    It is best to return the result (not use a pointer).
    That's what a return value is for.
    Whenever it fits the situation it's pretty much always best to use it.
    Code:
    #include <stdio.h>
     
    int search(const int *nums, int start, int end, int goal) {
        if (end - start < 1) return -1;
     
        int mid = (end - start) / 2 + start;
        if (nums[mid] == goal) return mid;
     
        // mid cannot be the goal, so don't include it
        return nums[mid] < goal
             ? search(nums, mid+1, end, goal)
             : search(nums, start, mid, goal);
    }
     
    int main() {
        int a[] = {2, 4, 5, 8, 10, 12, 15};
     
        for (int goal = 1; goal < 17; ++goal) printf("%2d ", goal);
        putchar('\n');
     
        for (int goal = 1; goal < 17; ++goal)
            printf("%2d ", search(a, 0, sizeof a / sizeof *a, goal));
        putchar('\n');
     
        return 0;
    }
    
    Output:
     1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 
    -1  0 -1  1  2 -1 -1  3 -1  4 -1  5 -1 -1  6 -1
    Last edited by john.c; 05-29-2023 at 08:26 PM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    808
    sorry its just dawned on me what you might of meant about prefacing variables....... i thought you meant int, float or double etc not my habit of using iNumber rather than Number

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Simplier:
    Code:
    int cmp_( const void *a, const void *b )
    { const int *p, *q; p = a; q = b; return (*p > *q ) - ( *p < *q ); }
    ...
    int a[] = { ... };
    int *p;
    int key = N;
    
    p = bsearch( &key, a, sizeof a / sizeof a[0], sizeof a[0], cmp_ );
    if ( ! p )
      puts ( "Not found" );
    else
      printf( "found @ %td\n", p - a );
    ...

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Simpler, if you discount the unnecessary obfuscation of the comparison function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    its just dawned on me what you might of meant about prefacing variables
    It's called Hungarian Notation and was originally invented for typeless languages, not a typed language like C. Microsoft used to use it but I don't think they recommend it anymore. Linus Torvalds calls it "brain-damaged".

    @flp, I should've mentioned the possibility of using bsearch, but I assumed that he wanted to implement his own function.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stddef.h>
     
    int cmpint(const void *a, const void *b) {
        const int *p = a, *q = b;
        return (*p > *q) - (*p < *q);
    }
     
    int main() {
        int a[] = {2, 4, 5, 8, 10, 12, 15};
     
        for (int key = 1; key < 17; ++key) printf("%2d ", key);
        putchar('\n');
     
        for (int key = 1; key < 17; ++key) {
            int *p = bsearch(&key, a, sizeof a / sizeof *a, sizeof *a, cmpint);
            printf("%2td ", p ? p - a : (ptrdiff_t)-1);
        }
        putchar('\n');
     
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recursive Binary Search
    By Tim Arevalo in forum C Programming
    Replies: 5
    Last Post: 07-30-2012, 12:37 PM
  2. [code] Recursive Search Function
    By anonytmouse in forum Windows Programming
    Replies: 1
    Last Post: 12-17-2004, 11:21 PM
  3. recursive search
    By bhorrobi in forum Windows Programming
    Replies: 2
    Last Post: 10-03-2003, 03:41 AM
  4. Recursive sequential search
    By supaben34 in forum C++ Programming
    Replies: 2
    Last Post: 10-10-2002, 11:06 AM
  5. Linear Search: the recursive way.
    By Nutshell in forum C Programming
    Replies: 7
    Last Post: 01-15-2002, 03:15 AM

Tags for this Thread