|
-
May 19th, 2006, 10:29 PM
#1
I have a project due and I really need some help now
Sorry to double post. I really some help with converting my binary search that works with ascending list to work with descending list.
here the code that works with ascending list
// See if the key is in the upper or lower half of the list and keep track of compares
// Until the middle equals the key
while((list[middle]!=key)&&(lower<=upper))
{compares=compares+1;
if (list[middle]>key)
upper=middle-1;
else
lower=middle+1;
middle=(lower+upper)/2;
}// End while
// The key is found tell the user its position
if (lower<=upper)
{tmp=middle+1;
cout<<"The key was found in position "<<middle+1<<"."<<endl;
cout<<"It took "<<compares<<" compares to find the value. "<<endl;
}// End if
// If the key isn't found return the dummy value
if (tmp==0)
return -1;
-
May 20th, 2006, 12:44 AM
#2
Re: I have a project due and I really need some help now
Interchange the statements "upper = middle - 1" and "lower = middle + 1". If list[n + 1] < list[n] for all n, then list[middle] > key means the key is at a higher index than middle, i.e you want to continue your search in the portion of list above middle.
-
May 20th, 2006, 01:05 AM
#3
Re: I have a project due and I really need some help now
First, you should never double post. Read the before you post thread. Second, use code tags to display your code. Third, make sure to give all the relevant information when you post. Looking at the code below, you forgot to initialize your variables (I made assumptions about how they were initialized). If you can (the code isn't very long), include a test program for your code.
Now I will try to answer your question. By a descending list, I think you mean a list that goes like 6,5,4,3,2,1. If you reverse a process, you can almost always just change your inequalities or the actions taken by them. For example, if you have >= change it to <=. Initialize upper to lower and lower to upper (You don't need to do this in your problem). You may have to rename few variables to keep the code readable. Let's look at a sample run of what would happen if you ran your code using a descending list of 6,5,4,3,2,1 with the key set to 2.
//initial values
lower = 0;
upper = 5;
middle = (0+5)/2 = 2;
//Loop tests to see if list[2] != 2. list[2] = 4 so the loop goes on
//The if statement returns true and sets new values
lower = 0;
upper = middle-1 = 1;
middle = (0+1)/2 = 0;
Oops, by subtracting one, we are heading away from you target! Now, you fix the problem. Good luck.
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
|