Binary Search
The first line contains an Integer 'N' which denotes the size of the array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
Third line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow..
All the 't' lines henceforth, will take the value of X to be searched for in the array/list.
For each test case, print the index at which X is present, -1 otherwise.
Output for every test case will be printed in a separate line.
Constraints :
1 <= t <= 10^4
0 <= N <= 10^6
0 <= X <= 10^9
Time Limit: 1 sec
Sample Input 1:
7
1 3 7 9 11 12 45
1
3
Sample Output 1:
1
Sample Input 2:
7
1 2 3 4 5 6 7
2
9
7
Sample Output 2:
-1
6
C++ code:
// arr - input array
// n - size of array
// val - element to be searched
int BinarySearch(int arr[], int n, int val){
int si=0;
int ei=n-1;
while(si<=ei)
{
int mid = (si+ei)/2;
if(arr[mid]==val)
{
return mid;
}
if(arr[mid]>val)
{
ei = mid-1;
}
else
si = mid+1;
}
return -1;
}
Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.
0 comments:
Post a Comment