Given an input a[]={5,3,2,1,0}, key=1, what is position of key element ( assume binary search)
Question
Given an input
a[]={5,3,2,1,0},
key=1,
what is position of key element ( assume binary search)
Solution
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. However, for Binary Search to work, the array must be sorted.
The given array is a[]={5,3,2,1,0}, which is not sorted. Therefore, we cannot use binary search directly.
If we sort the array in ascending order, we get a[]={0,1,2,3,5}.
Now, we can perform binary search to find the key=1.
Here are the steps for binary search:
-
Find the middle element of the array. In this case, the middle element is 2 (at index 2).
-
Since the key=1 is less than the middle element, we discard the right half of the array. Now, our array becomes a[]={0,1}.
-
Again, find the middle element of the array. Now, the middle element is 0 (at index 0).
-
Since the key=1 is greater than the middle element, we discard the left half of the array. Now, our array becomes a[]={1}.
-
The remaining element is exactly our key, so we have found the key at index 1 (in the sorted array).
Please note that the original position of key=1 in the unsorted array a[]={5,3,2,1,0} was at index 3.
Similar Questions
Suppose following numbers are sorted in an array A:32,51,26,84,63,21,11,54Using Binary search find the location of item 26,11 and 99.Answer text
If the array contains duplicate elements, which index will binary search return for the key?
Program to demonstrate the use of Binary Search to search a given element in a sorted array in ascending order.
given an array a[] = {4,6,7,8,11} and key =11, what is the level of recursion?( assume binary search)5432
In a binary search, the elements of the array must be in which order?Group of answer choicesAll options are correctAscending orderRandom orderDescending order
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.