Skip to content

Commit 42007c8

Browse files
authored
docs: improve LinearSearch documentation with examples and step-by-step explanation (#7435)
1 parent e49cd55 commit 42007c8

1 file changed

Lines changed: 30 additions & 5 deletions

File tree

src/main/java/com/thealgorithms/searches/LinearSearch.java

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,34 @@
1010
*
1111
* It works for both sorted and unsorted arrays.
1212
*
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>
1337
* 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
1741
*
1842
* Space Complexity: O(1)
1943
*
@@ -25,9 +49,10 @@
2549
public class LinearSearch implements SearchAlgorithm {
2650

2751
/**
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.
2954
*
30-
* @param array List to be searched
55+
* @param array List to be searched (can be unsorted)
3156
* @param value Key being searched for
3257
* @return Location of the key, -1 if array is null or empty, or key not found
3358
*/

0 commit comments

Comments
 (0)