|
-
October 30th, 2007, 09:31 PM
#1
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;
}
-
October 30th, 2007, 10:09 PM
#2
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.
-
October 30th, 2007, 11:23 PM
#3
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.).
-
October 30th, 2007, 11:48 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|