Knowee
Questions
Features
Study Tools

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)

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. Find the middle element of the array. In this case, the middle element is 2 (at index 2).

  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}.

  3. Again, find the middle element of the array. Now, the middle element is 0 (at index 0).

  4. Since the key=1 is greater than the middle element, we discard the left half of the array. Now, our array becomes a[]={1}.

  5. 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.

This problem has been solved

Similar Questions

Given an array of integers nums sorted in non-decreasing order, write a program to find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. Do it using binary search.Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4]Explanation: The first occurrence of 8 is at index 3 and last occurrence of 8 is 4

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

What happens if the search key is not present in the array in a Binary Search algorithm?The algorithm returns the closest value.The algorithm returns 1 or an equivalent value.The algorithm keeps searching indefinitely.The algorithm returns the last element.

If the array contains duplicate elements, which index will binary search return for the key?

Write a program to perform binary search on a list of integers given below, to search for an element input by the user. If it is found display the element along with its position, otherwise display the message "Search element not found".5, 7, 9, 11, 15, 20, 30, 45, 89, 97

1/3

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.