Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

SEARCHING

PREREQUISITES:
1. Arrays
2. Complexity Analysis

MOTIVATIONAL PROBLEM:
Input N distinct numbers and print the index where value S is present. Assume for the time
being S will always be present at some index.
*N and S are both integers inputted by the user.

LINEAR SEARCH:
Most of you would have created an int array of size N and accepted N numbers from the user.
Then you would run a loop from 0 to N-1, and check whether the element at each index is S or
not. If S, you break from the loop and report the answer. Else you continue with the loop.
But what is the complexity of this? O(N).

Now I tell you that the sequence the user inputs is sorted. Can you improve the complexity?

BINARY SEARCH:
You can read the following article once you are thorough with the aforementioned prerequisites.
But don’t read the whole of it! Stop before the following lines:
“​Note that this assumes that we have random access to the sequence. Trying to use binary
search on a container such as a linked list makes little sense and it is better use a plain
linear search instead.”
These lines are present after the paragraph on Complexity below the code.

Link to the article :


https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/

Can you write C++ code to implement binary search. Wait. Now I remove the constraint that S
will always be present in the inputted sequence. If S is not present in the inputted sequence
report the answer to be -1.
Go ahead and give it a try! Take help from the pseudo code in the above tutorial.
Here is the solution: ​https://ideone.com/h98T78

Think:
What if I modified the problem and asked you to report me the smallest index such that the
value at that index is greater than or equal to S? If there are no elements greater than or equal
to S in the array report -1.The array is sorted as usual. You’ve got to use binary search!
What changes will you make to the code?
Hint: What if I get the value of A[mid] >= S? Well mid can be my answer(after all we have to
report the index of the element greater than or equal to S). It may not be my answer as well.
What if there is a value at mid-1 which is also >=S? So we make mid the answer for the time
being(by making pos=mid). But we try to better it, by searching the lower half. If I don’t get any
value >=S, then mid would remain my answer. But if I get an index where the value there is >=S
our answer will be overwritten by this index. Makes sense?
What if I get the value of A[mid] < S? Clearly that’s not good enough. We cannot make mid the
answer for the time being by making pos=mid. So search the upper half.
Extend this idea to get the full solution.

You might also like