|
10 | 10 | * |
11 | 11 | * It works for both sorted and unsorted arrays. |
12 | 12 | * |
| 13 | + * <p>How it works step-by-step: |
| 14 | + * <ol> |
| 15 | + * <li>Start from the first element of the array.</li> |
| 16 | + * <li>Compare the current element with the target value.</li> |
| 17 | + * <li>If they match, return the current index.</li> |
| 18 | + * <li>If they don't match, move to the next element.</li> |
| 19 | + * <li>Repeat until the element is found or the array ends.</li> |
| 20 | + * <li>If not found, return -1.</li> |
| 21 | + * </ol> |
| 22 | + * |
| 23 | + * <p>Example: |
| 24 | + * <pre> |
| 25 | + * Input array: [5, 3, 8, 1, 9] |
| 26 | + * Target: 8 |
| 27 | + * |
| 28 | + * Step 1: Compare 5 with 8 → no match, move on |
| 29 | + * Step 2: Compare 3 with 8 → no match, move on |
| 30 | + * Step 3: Compare 8 with 8 → match found at index 2! |
| 31 | + * |
| 32 | + * Output: 2 |
| 33 | + * |
| 34 | + * If target = 7: |
| 35 | + * Output: -1 (not found) |
| 36 | + * </pre> |
13 | 37 | * Time Complexity: |
14 | | - * - Best case: O(1) |
15 | | - * - Average case: O(n) |
16 | | - * - Worst case: O(n) |
| 38 | + * - Best case: O(1) - target is the first element |
| 39 | + * - Average case: O(n) - target is somewhere in the middle |
| 40 | + * - Worst case: O(n) - target is last or not present |
17 | 41 | * |
18 | 42 | * Space Complexity: O(1) |
19 | 43 | * |
|
25 | 49 | public class LinearSearch implements SearchAlgorithm { |
26 | 50 |
|
27 | 51 | /** |
28 | | - * Generic Linear search method |
| 52 | + * Generic Linear search method that searches for a value |
| 53 | + * in the given array by checking each element one by one. |
29 | 54 | * |
30 | | - * @param array List to be searched |
| 55 | + * @param array List to be searched (can be unsorted) |
31 | 56 | * @param value Key being searched for |
32 | 57 | * @return Location of the key, -1 if array is null or empty, or key not found |
33 | 58 | */ |
|
0 commit comments