problem no 19: Binary search.

 QUESTION:

Binary Search
Basic Accuracy: 38.43% Submissions: 69401 Points: 1

Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search.


Example 1:

Input:
N = 5
arr[] = {1 2 3 4 5} 
K = 4
Output: 3
Explanation: 4 appears at index 3.


Example 2:

Input:
N = 5
arr[] = {11 22 33 44 55} 
K = 445
Output: -1
Explanation: 445 is not present.
 
 
 
ANSWER:
//the below function will be called when needed. 
int binsearch(int array[],int start_index,int end_index,int element)
{
if(end_index>=start_index)
{
int middle=start_index+(end_index-start_index)/2;
if(array[middle]==element)
{
return middle;
}
if(array[middle]>element)
{
return binsearch(array,start_index,middle-1,element);
}
else
{
return binsearch(array,middle+1,end_index,element);
}
}
return -1;
}
 
 
 //below is the main function that we are gonna solve.
int binarysearch(int arr[], int n, int k){

int i=0,j=n-1;

int loc=binsearch(arr,i,j,k);
return loc;
}

 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.