Advertisement
kot_mapku3

Binary search

May 7th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int recursion(int* a, int key, int l, int r) {
  7.     int middle = (l + r) / 2;
  8.     cout << "middle: " << middle << ", left: " << l << ", right: " << r << endl;
  9.     if (a[middle] == key) return middle;
  10.     if (l == middle || r == middle) return -1;
  11.     if (key < a[middle]) return recursion(a, key, l, middle);
  12.     if (key > a[middle]) return recursion(a, key, middle, r);
  13. }
  14.  
  15. int iterative(int* a, int key, int l, int r) {
  16.     int middle = (l + r) / 2;
  17.     while (true) {
  18.         cout << "middle: " << middle << ", left: " << l << ", right: " << r << endl;
  19.         middle = (l + r) / 2;
  20.         if (key < a[middle]) r = middle - 1;
  21.         else if (key > a[middle]) l = middle + 1;
  22.         else return middle;
  23.  
  24.         if (l > r) return -1;
  25.     }
  26. }
  27.  
  28. int main() {
  29.     int a[19] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 };
  30.  
  31.     cout << "recursion => " << endl;
  32.     cout << recursion(a, 3, 0, 18) << endl;
  33.     cout << "iterative => " << endl;
  34.     cout << iterative(a, 3, 0, 18) << endl;
  35.  
  36.     system("pause");
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement