//function
      /* arr = array
      	 n = size of array
         k = element to be found
      */
      int binarySearch(int arr[], int n, int k) {
        //first and last element intialization
        int first = 0, last = n - 1;
        while(first <= last) {
          //mid value of array which will be compared 
          int mid = first + (last - first) / 2;
          // If the element is present at the middle itself
          if(arr[mid] == k) 
            return mid;
          // If element is smaller than mid, then it can only be present in left subarray
          else if(arr[mid] > k) 
            last = mid - 1;
          // If element is larger than mid, then it can only be present in right subarray
          else 
            first = mid + 1
          }
        // If element not found then return -1
        return -1;
      }
      

      Cpp language logo
      Binary Search

      binarysearch
      recursion

      A recursive binary search function. It returns location of x in given array arr[l..r] is present, otherwise -1

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.