Question

a. You need write a sequential search algorithm that is recursive format. b. Write a binary...

a. You need write a sequential search algorithm that is recursive format. b. Write a binary search algorithm that is recursive, then write the program to implement it.

C++

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

#include<iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
  
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
  
// If element is smaller than mid, than search left side else right side
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}

//-1 if does not exist
return -1;
}
int binary_search_rec(int *p,int n,int x){
return binarySearch(p,0,n-1,x);
}

int linear_search_rec(int arr[], int n ,int key){
if(n<0) { // Base case - not found
return -1;
}
if(arr[n]==key) { // Base case - found
return n;
}
// Recursive case
return linear_search_rec(arr, n-1, key);
}
int main()
{
int arr[] = {10,20,30,55,67,88,98,110,150,170};
int size = 10;
int x=67;
int result = binary_search_rec(arr,size, x);
(result == -1) ? cout << "Element "
: cout << "Element is present at index " << result;

cout<<endl<<endl;
result = linear_search_rec(arr, size - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
  
return 0;
}

Note : Please comment below if you have concerns. I am here to help you

If you like my answer please rate and help me it is very Imp for me

Add a comment
Know the answer?
Add Answer to:
a. You need write a sequential search algorithm that is recursive format. b. Write a binary...
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