Sorting Algorithms

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Nov 2009
Posts: 1
Reputation: saintrenz is an unknown quantity at this point 
Solved Threads: 0
saintrenz saintrenz is offline Offline
Newbie Poster

Sorting Algorithms

 
0
  #1
Nov 6th, 2009
I need Help!

Consider this following modified version of the binary search algorithm. (Modifications are indicated by a comment highlighted asterisks.) With this new version of the binary search algorithmn work correctly for all data? If not, specify a situiation in which this version will fail.

  1. template<class element, class Keytype>
  2. bool binarySearch(const apvector<element> &list, int n, Keytype target, element &object)
  3.  
  4. {
  5. int low, middle, high;
  6. bool found = false;
  7.  
  8. low = 0;
  9. high = n;
  10. while ((low <= high) && ! found)
  11. {
  12. middle = (low + high) / 2;
  13. if(list[middle] = target)
  14. found=true;
  15. else if (list[middle] < target)
  16. low = middle; // *** MODIFICATION HERE ***
  17. else
  18. high = middle; // *** MODIFICATION HERE ***
  19. }
  20. if (found)
  21. object=list[middle];
  22. return found;
  23. }
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 15,546
Reputation: Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute 
Solved Threads: 1483
Team Colleague
Featured Poster
Ancient Dragon's Avatar
Ancient Dragon Ancient Dragon is offline Offline
Still Learning
 
-7
  #2
Nov 6th, 2009
1) Line 13 is wrong. It should use the == boolean operator, not the = assignment operator.

>>If not, specify a situiation in which this version will fail.

I can think of three kinds of data for which that algorithm will fail. If you think about the different kinds of data then you should be able to list at least one of them too.
Last edited by Ancient Dragon; Nov 6th, 2009 at 9:14 am.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC