Advertisement
reellearning

Binary Search

Jun 30th, 2012
14,663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1.  
  2. /*
  3.  * binarysearch.cpp
  4.  *
  5.  *  Created on: Jun 29, 2012
  6.  *      Author: Derek
  7.  *
  8.  *  Example of the binary search algorithm
  9.  */
  10.  
  11. #include <iostream>
  12.  
  13. using namespace std;
  14.  
  15. int binarySearch(int array[], int size, int searchValue)
  16. {
  17.     int low = 0;
  18.     int high = size - 1;
  19.  
  20.     int mid;
  21.  
  22.     while (low <= high)
  23.     {
  24.         mid = (low + high) / 2;
  25.  
  26.         if(searchValue == array[mid])
  27.         {
  28.             return mid;
  29.         }
  30.         else if (searchValue > array[mid])
  31.         {
  32.             low = mid + 1;
  33.         }
  34.         else
  35.         {
  36.             high = mid - 1;
  37.         }
  38.     }
  39.  
  40.     return -1;
  41.  
  42. }
  43.  
  44. int main()
  45. {
  46.     int a[] = {12, 22, 34, 47, 55, 67, 82, 98};
  47.  
  48.     int userValue;
  49.  
  50.     cout << "Enter an integer: " << endl;
  51.     cin >> userValue;
  52.  
  53.     int result = binarySearch(a, 8, userValue);
  54.  
  55.     if(result >= 0)
  56.     {
  57.         cout << "The number " << a[result] << " was found at the"
  58.                 " element with index " << result << endl;
  59.     }
  60.     else
  61.     {
  62.         cout << "The number " << userValue << " was not found. " << endl;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement