Answer to Question #235346 in C++ for Myname

Question #235346
Design a recursive algorithm to search a sorted array a for an element x between a[low] and
a[high]. If no element is found it returns -1.
1
Expert's answer
2021-09-10T01:47:47-0400
#include<iostream>
using namespace std;






int searchElement(int a[], int low, int high, int x)
{
	if (high >= low) {
		int middle = low + (high - low) / 2;
		// If the x is present at the middle itself
		if (a[middle] == x)
			return middle;


		// If the current x number is greater than x, then x is on the low side of the current x
		if (a[middle] > x)
			return searchElement(a, low, middle - 1, x);


		// otherwise x is on the right side of the current x.
		return searchElement(a, middle + 1, high, x);
	}
	return -1;
}


int main()
{


	int a[]={5,4,8,955,6,2,3,4,5,60};
	int x;


	cout<<"Enter element ot search: ";
	cin>>x;


	
	if(searchElement(a,0,10,x)!=-1){
		printf("\nElement is present in the array.\n\n");	
	}else{
		printf("\nElement is NOT present in the array.\n\n");	
	}


	cin>>x;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS