CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2007
    Posts
    2

    C++ Search Problems

    The following code below takes an array of string items (tokens) and searches for the lexographically largest, well it should anyways. The problem is that the program seems to reach the base case just fine, hand back and do the first comparison than BOOM. The stack dumps. No warnings or anything. Any ideas on what is going wrong?
    Code:
    std::string& largestWord(std::string items[],int numberWords){
        int middle = numberWords/2;
        std::string& rightLWord = largestWord(items, middle+1,numberWords);
        std::string& leftLWord = largestWord(items, 0, middle);
        if(leftLWord >= rightLWord){
            return leftLWord;
        }
         return rightLWord;
    }
    
    std::string& largestWord(std::string items[],int left,int right){
        if(right == left){
            return items[left];
        }
        int middle = ( (left+right)/2 );    
        std::string& leftLWord = largestWord(items,left,middle);
        std::string& rightLWord = largestWord(items,middle+1,right);
        if(leftLWord >= rightLWord){
            return leftLWord;
        }
        return rightLWord;
    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: C++ Search Problems

    I can't quite follow what you are doing. It almost looks like you
    are doing some type of binary search. But if they are already
    sorted, you would just return the last element.

    You can use std::max_element in <algorithm> to find the
    largest element.

  3. #3
    Join Date
    Oct 2007
    Posts
    2

    Re: C++ Search Problems

    It is binary search based just for kicks (I am in a beginners C++ class but very knowledgeable of in java, php,javascript, etc.).

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: C++ Search Problems

    You can't use binary search unless your list is already sorted. If it is, finding the max element is trivial. If not, why would binary search work? Think about it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured