Advertisement
CHU2

Recursive Binary Search

Feb 18th, 2023 (edited)
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;    //gumamit naak std ffs ;<
  4.  
  5. int binarysearch(const int, int array[], int, int, int);
  6.  
  7. int main(){
  8.     const int size = 5;
  9.     int array[size] = {2, 3, 4, 10, 40};
  10.     int search = 10;    //search in array
  11.    
  12.     int searchindex = binarysearch(size, array, search, 0, 0);    //added 00 as tally numbers for recursive looping
  13.    
  14.     if (searchindex != -1){
  15.         cout << "Element " << array[searchindex] << " present at index " << searchindex;
  16.     }
  17.     else {
  18.         cout << "Element is not present in array";
  19.     }
  20.    
  21.     return 0;
  22. }
  23.  
  24. int binarysearch(const int size, int array[], int search, int h, int i){
  25.     if (h < size){    //condition else search value isn't on any array index
  26.         int middle = (((size -h) /2) +i);    //an tally kanina para adto dd ha calculations
  27.        
  28.         if (array[middle] == search){
  29.             return middle;
  30.         }
  31.         else if (array[middle] < search){
  32.             h = middle;    //increase tally
  33.             i = middle;
  34.            
  35.             if (h == 4){    //deja vu, parihas reason han interative kanina
  36.                 h++;
  37.             }
  38.            
  39.             return binarysearch(size, array, search, h, i);    //return with new tally numbers
  40.         }
  41.         else if (array[middle] > search){
  42.             h = middle;
  43.            
  44.             if (h == 1){    //same reason as line 39
  45.                 h = 4;
  46.             }
  47.             else if (h == 0){    //same reason as line 44
  48.                 h = 5;
  49.             }
  50.            
  51.             return binarysearch(size, array, search, h, i);
  52.         }
  53.     }
  54.    
  55.     return -1;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement