Thread: Recursive sequential search

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    92

    Recursive sequential search

    Hi there all,
    I have to implement a recursive sequential that searches for an element in an UNSORTED array and displays the position of that element. This is my code so far.
    Code:
    //'listSize' is a parameter that inputs size of the array into function 
    //'item' is a parameter that inputs the current value of the function
    //list is the array itself and therefore is also a pointer
    //returns the position of the array that we are searching for
    
      int sequentialSearch(int item, int* list, int listSize){
        if (listSize == 0){
          return -1;
        }
        if (*list == item){//if first element is equal to listSize
          return 0;
        }
        
        else sequentialSearch(int item, int* list, int listSize){
          list = list + 1;
        }
      }
    If there is no matching elements we are supposed to return a -1. Would someone please help me with this? Thank you.

  2. #2
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    You need to reduce the list by one item.

    If( item == *list) // ot sure if this is what you want, but some comparison to see if you have found your item
    {
    // found code
    return(0);
    }
    else
    {
    sequentialSearch(item, list[1], listSize);
    }


    You have to think of each call to your function independently. Don't think about the recursion. Just think my function will check if the item that is passed equals the first item in my list. If so I found it. Otherwise I will call the function but without the item that I know is not it.
    Best Regards,

    Bonkey

  3. #3
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    Don't follow the section of your code which goes:

    else sequentialSearch(int item, int* list, int listSize){
    list = list + 1;


    However, I think I get what you're trying to do.

    So who say you have to implement a sequential search in this way? This is terrible. If your list is big, then stack overflow errors will ensue.

    Why not just run down a for loop checking for list[n] == item?
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [code] Recursive Search Function
    By anonytmouse in forum Windows Programming
    Replies: 1
    Last Post: 12-17-2004, 11:21 PM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM