Java Notes
Complete guide to searching algorithms — Linear Search, Binary Search, variations, two-pointer technique, and search problems with Java implementations.
Linear Search — O(n)
Binary Search — O(log n)
Prerequisite: Array must be sorted.
| Step 1: left=0, right=6, mid=3 | arr[3]=7 → FOUND! |
| Step 1: left=0, right=6, mid=3 | arr[3]=7 < 9 → search right |
| Step 2: left=4, right=6, mid=5 | arr[5]=11 > 9 → search left |
| Step 3: left=4, right=4, mid=4 | arr[4]=9 → FOUND! |
Two Pointer Technique
Interview Questions
Q1: When would you use Linear Search over Binary Search?
Answer: When data is unsorted (sorting for binary search costs O(n log n) — not worth it for single search), small arrays (n < 20), or linked lists (no random access for binary search).
Q2: Why use left + (right - left) / 2 instead of (left + right) / 2?
Answer: To prevent integer overflow. If left and right are both near Integer.MAX_VALUE, their sum overflows to a negative number. The subtraction form avoids this.
Q3: What is the time complexity of Binary Search?
Answer: O(log n). Each comparison eliminates half the remaining elements. For n=1,000,000 it takes at most 20 comparisons (log₂(1,000,000) ≈ 20).
Q4: How do you find the peak element in a mountain array?
Answer: Binary search: if arr[mid] < arr[mid+1], peak is to the right (left = mid+1). Otherwise, peak is at mid or left (right = mid). Time: O(log n).
Q5: Can Binary Search be applied to non-array problems?
Answer: Yes! "Binary search on the answer" applies when: the answer space is monotonic (sorted), and you can verify a candidate answer in O(n) or less. Examples: minimum capacity, maximum minimum distance, finding sqrt.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Searching Algorithms in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, dsa, searching, searching algorithms in java
Related Java Master Course Topics