Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions src/main/java/com/thealgorithms/searches/LinearSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,34 @@
*
* It works for both sorted and unsorted arrays.
*
* <p>How it works step-by-step:
* <ol>
* <li>Start from the first element of the array.</li>
* <li>Compare the current element with the target value.</li>
* <li>If they match, return the current index.</li>
* <li>If they don't match, move to the next element.</li>
* <li>Repeat until the element is found or the array ends.</li>
* <li>If not found, return -1.</li>
* </ol>
*
* <p>Example:
* <pre>
* Input array: [5, 3, 8, 1, 9]
* Target: 8
*
* Step 1: Compare 5 with 8 → no match, move on
* Step 2: Compare 3 with 8 → no match, move on
* Step 3: Compare 8 with 8 → match found at index 2!
*
* Output: 2
*
* If target = 7:
* Output: -1 (not found)
* </pre>
* Time Complexity:
* - Best case: O(1)
* - Average case: O(n)
* - Worst case: O(n)
* - Best case: O(1) - target is the first element
* - Average case: O(n) - target is somewhere in the middle
* - Worst case: O(n) - target is last or not present
*
* Space Complexity: O(1)
*
Expand All @@ -25,9 +49,10 @@
public class LinearSearch implements SearchAlgorithm {

/**
* Generic Linear search method
* Generic Linear search method that searches for a value
* in the given array by checking each element one by one.
*
* @param array List to be searched
* @param array List to be searched (can be unsorted)
* @param value Key being searched for
* @return Location of the key, -1 if array is null or empty, or key not found
*/
Expand Down
Loading