Question

can anyone help me how to write binary search program in c++ that return multiple index.For...

can anyone help me how to write binary search program in c++ that return multiple index.For instance
if i have 124564.It should give the index of both for value 4 .
0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

Please note firstly your example is wrong. Binary search uses sorted array to find index. Also, if there are let's say 7 4's then program should return the first and last 4 index because all other would be in between since array is sorted.

#include<bits/stdc++.h>
using namespace std;
  
/* if x is present in arr[] then returns the index of
FIRST occurrence of x in arr[0..n-1], otherwise
returns -1 */
int first(int arr[], int low, int high, int x, int n)
{
if(high >= low)
{
int mid = low + (high - low)/2;
if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x)
return mid;
else if(x > arr[mid])
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid -1), x, n);
}
return -1;
}
  
  
/* if x is present in arr[] then returns the index of
LAST occurrence of x in arr[0..n-1], otherwise
returns -1 */
int last(int arr[], int low, int high, int x, int n)
{
if (high >= low)
{
int mid = low + (high - low)/2;
if (( mid == n-1 || x < arr[mid+1]) && arr[mid] == x)
return mid;
else if (x < arr[mid])
return last(arr, low, (mid -1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
  
// Driver program
int main()
{
int arr[] = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8};
int n = sizeof(arr)/sizeof(int);
  
int x = 8;
cout<<"First Occurrence = "<<first(arr, 0, n-1, x, n);
cout<<"\nLast Occurrence = "<<last(arr, 0, n-1, x, n)<<endl;
  
return 0;
}

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
can anyone help me how to write binary search program in c++ that return multiple index.For...
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