-
Notifications
You must be signed in to change notification settings - Fork 0
LinearSearch
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement a linear search algorithm that finds the position of a target value within an array.
Linear search is the simplest searching algorithm that checks every element in the array sequentially until the target element is found or the end of the array is reached.
- Time Complexity: O(n) - where n is the number of elements
- Space Complexity: O(1) - no extra space needed
- Best for: Small datasets or unsorted arrays
- Start from the first element
- Compare each element with the target
- If a match is found, return the index
- If no match is found after checking all elements, return -1
Implement the following methods in LinearSearch.java:
-
search(int[] arr, int target)- Search for an integer in an array -
search(String[] arr, String target)- Search for a string in an array
- Empty array
- Target at the beginning
- Target at the end
- Target in the middle
- Target not in array
- Array with duplicates (return first occurrence)
- Think about what to return when the array is empty
- Remember to check array bounds
- Consider using a simple for loop
- What happens if the array is null?
- How would you modify this to find all occurrences of the target?
- Can you optimize this for sorted arrays? (Hint: What other search algorithm would be better?)
- How would you handle null values in the array?
- Binary Search (for sorted arrays)
- Jump Search
- Interpolation Search