Advertisement
Guest User

Untitled

a guest
May 21st, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. template <class elemType>
  2. int binarySearch(const elemType list[], int length,
  3. int& comparisons, const elemType& searchItem)
  4. {
  5. // TODO
  6. int mid = -1;
  7. int min = 0;
  8. int max = length - 1;
  9. while (max >= min)
  10. {
  11. mid = (max + min) / 2;
  12. comparisons++;
  13. if (searchItem == list[mid]) // if value is found, return the position
  14. {
  15. return mid;
  16. }
  17. else if (searchItem < list[mid])
  18. {
  19. comparisons++;
  20. max = mid - 1;
  21. }
  22. else
  23. {
  24. comparisons++;
  25. min = mid + 1;
  26. }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement