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)102Error

Question

Given an input

a[]={5,3,2,1,0},

key=1,

what is position of key element (assume binary search)

102Error

🧐 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 on this array.

If we sort the array in ascending order, we get a[]={0,1,2,3,5}. Now, we can apply 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 ignore the right half of the array and consider the left half for the next step. Now, our array becomes a[]={0,1}.

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

  4. Since the key=1 is greater than the middle element, we ignore the left half of the array and consider the right half for the next step. Now, our array becomes a[]={1}.

  5. The middle (and only) element of this array is 1, which is equal to the key. Therefore, we have found the key at index 1 (in the sorted array).

So, the position of the key element (1) in the sorted array is 1. However, in the original unsorted array a[]={5,3,2,1,0}, the position of the key element (1) is 3.

This problem has been solved

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

given an array a[] = {4,6,7,8,11} and key =11, what is the level of recursion?( assume binary search)5432

Write a Python program to find the Index position of a specified element and print it. And if the specified element is not present then print -1 as

Program to demonstrate the use of Binary Search to search a given element in a sorted array in ascending order.

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

1/1

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.