Linear Search can be implemented for sorting and non-sorting elements of a Data structure particular Data structure but the average case time complexity is O(n). Whereas as Binary Search can be implemented only when the items are in sorted order and average-case time complexity is O(logn) and both Transversal have best-case Time complexity is O(1). Now, given an Array List containing sorted elements Check whether the element exists in the ArrayList or not.
There are two types of Transversal while searching elements in Linear Data structure.
Input: ArrayList:[1, 2, 3, 4, 6, 7, 8, 9] key:3 Output: true
Case 1: Use Binary Search Because the list is sorted in order and Binary Search has less average time complexity as compared to Linear Search i.e O(logn).
Case 2: Suppose in order to find the maximum index of the greatest element less than the key in sorted repeated elements of ArrayList Using Binary Search.
Input: List: [2, 3, 3, 4, 4, 5, 6, 7] key: 2 key: 4 Output: -1 2
Example: Modify the Binary Search according to the condition
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.