Answer to Question #276193 in C for MRM

Question #276193

Given an array arr[] sorted in ascending order of size N and an integer K. Check if K is present in the array or not. (Use Binary Search)

Input: N = 5 K = 6 arr[] = {1,2,3,4,6}

Output: 1

Explanation: Since, 6 is present in the array at index 4 (0-based indexing),

Output is 1 


1
Expert's answer
2021-12-09T07:30:00-0500
#include <stdio.h>


int binarySearch(int arr[], int element, int r, int x)
{
	if (r >= element) {
		int midPosition = element + (r - element) / 2;




		if (arr[midPosition] == x)
			return midPosition;




		if (arr[midPosition] > x)
			return binarySearch(arr, element, midPosition - 1, x);




		return binarySearch(arr, midPosition + 1, r, x);
	}




	return -1;
}


int main()
{
	int  arr[] = {1,2,3,4,6};
	int n = 5;
	int K = 6;
	int result = binarySearch(arr, 0, n - 1, K);
	if(result == -1){
		printf("Not present in array");
	}else{
		printf("Output %d", 1);
	}


	getchar();
	getchar();
	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