Given an array of n distinct integers and an element x. Search the element x in the array using minimum number of comparisons. Any sort of comparison will contribute 1 to the count of comparisons. For example, the condition used to terminate a loop, will also contribute 1 to the count of comparisons each time it gets executed. Expressions like while (n) {n–;} also contribute to the count of comparisons as value of n is being compared internally so as to decide whether or not to terminate the loop.
Examples:
|
Asked in Adobe Interview
Recommended: Please try your approach on{IDE}first, before moving on to the solution.
Below simple method to search requires2n + 1comparisons in worst case.
|
How to reduce number of comparisons?
The idea is to copy x (element to be searched) to last location so that one last comparison when x is not present in arr[] is saved.
Algorithm:
|
|
Output:
|
Time Complexity: O(n)
Number of Comparisons: atmost(n+2)comparisons
This article is contributed byAyush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article usingcontribute.geeksforgeeks.orgor mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Source: http://www.geeksforgeeks.org/search-element-unsorted-array-using-minimum-number-comparisons/