Question

6. Let T(1..n] be a sorted array of distinct integers, some of which may be negative. Give an algorithm that can find an inde

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ALGORITHM:-

  1. Compare mid with the middle element.
  2. If mid matches with middle element, we return the mid index.
  3. Else If mid is greater than the mid element, then mid can only lie in right half subarray after the mid element. So we recur for right half.
  4. Else (mid is smaller) recur for the left half.

Calculating Time complexity:

  • Hence, the time complexity of Binary Search is

    log2 (n)

    • Let say the iteration in Binary Search terminates after k iterations. In the above example, it terminates after 3 iterations, so here k = 3
    • At each iteration, the array is divided by half. So let’s say the length of array at any iteration is n
    • At Iteration 1,
      Length of array = n
    • At Iteration 2,
      Length of array = n2
    • At Iteration 3,
      Length of array = (n2)2 = n22
    • Therefore, after Iteration k,
      Length of array = n2k
    • Also, we know that after
      After k divisions, the length of array becomes 1
    • Therefore
      Length of array = n2k = 1
      => n = 2k
      
    • Applying log function on both sides:
      => log2 (n) = log2 (2k)
      => log2 (n) = k log2 (2)
      
    • As (loga (a) = 1)
      Therefore,
      => k = log2 (n)
      

PROGRAM:-

// C++ program to check fixed point
// in an array using binary search
#include <iostream>
using namespace std;

int binarySearch(int arr[], int low, int high)
{
   if(high >= low)
   {
       int mid = (low + high)/2; /*low + (high - low)/2;*/
       if(mid == arr[mid])
           return mid;
       if(mid > arr[mid])
           return binarySearch(arr, (mid + 1), high);
       else
           return binarySearch(arr, low, (mid -1));
   }

   /* Return -1 if there is no Fixed Point */
   return -1;
}

/* Driver code */
int main()
{
   int arr[10] = {-10, -1, 0, 3, 10, 11, 30, 50, 100};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Fixed Point is "<< binarySearch(arr, 0, n-1);
   return 0;
}


OUTPUT:-

Fixed Point is 3
Add a comment
Know the answer?
Add Answer to:
6. Let T(1..n] be a sorted array of distinct integers, some of which may be negative....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT