Question

1. Design and write a Divide& Conquer algorithm that, given an array A of n distinct integers which is already sorted into ascending order, will find if there is some i such that Ali] in worst-case 0(log n) time.

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

#include <bits/stdc++.h>

using namespace std;

int binarySearch(int arr[], int low, int high)

{

if(high >= low)

{

int mid = (low + high)/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;

}

int main()

{

int arr[100000],i,n,k;

cout<<"Enter no of distinct elements in the array : ";

cin>>n;

cout<<"Enter the elements in ascending order"<<endl;

for(i=0;i<n;i++)

cin>>arr[i];

k=binarySearch(arr,0,n);

cout<<k<<" // ar["<<k<<"] = "<<k<<endl;

return 0;

}

The above program returns a Fixed Point in the array, if there is any Fixed Point present in array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i.

Add a comment
Know the answer?
Add Answer to:
1. Design and write a Divide& Conquer algorithm that, given an array A of n distinct...
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