Binary Search

    0

    0

    ank1traj

    binarysearchrecursion

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

    //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;
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.