Quirinus

BinarySearch function

Oct 12th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.35 KB | None | 0 0
  1. int BinarySearch(int a[], int length, int key)
  2. {
  3.     int left = 0;
  4.     int right = length - 1;
  5.     int middle;
  6.  
  7.     do
  8.     {
  9.         middle = (left + right) / 2;
  10.        
  11.         if (a[middle] == key)
  12.         {
  13.             return middle;
  14.         }
  15.         else if (a[middle] < key)
  16.         {
  17.             left = middle + 1;
  18.         }
  19.         else
  20.         {
  21.             right = middle - 1;
  22.         }
  23.     }
  24.     while (left <= right);
  25.  
  26.     return -1;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment