Searching, Min/Max & Reverse
Implement linear search, compute min/max in one pass, and reverse arrays in-place or by copy.
Linear Search
Linear search checks each element in order until it finds the target.
- Return the index when found
- If not found, return
-1 - Stop early with
break
public class Main {
public static void main(String[] args) {
// Example array
int[] a = {5, 8, 9, 12, 15};
int t = 9; // target value to search
int idx = -1; // will stay -1 if not found
// Loop through each index of the array
for (int i = 0; i < a.length; i = i + 1) {
// Check if current element matches the target
if (a[i] == t) {
idx = i; // store the index where found
break; // exit loop early (found the target)
}
}
// Print result
if (idx != -1) {
System.out.println("Found " + t + " at index " + idx);
} else {
System.out.println(t + " not found in array");
}
}
}
findIndex()
Encapsulate search in a method:
public class Main {
public static void main(String[] args) {
// Example array
int[] a = {5, 8, 9, 12, 15};
int t = 9; // target value we are searching for
int idx = -1; // default index (-1 means "not found")
// Loop through each index of the array
for (int i = 0; i < a.length; i = i + 1) {
// Check if current element matches the target
if (a[i] == t) {
idx = i; // store the index where it was found
break; // stop searching (first match found)
}
}
// Print result
if (idx != -1) {
System.out.println("Found " + t + " at index " + idx);
} else {
System.out.println(t + " not found in array");
}
}
}
All lessons in this course
- Array Basics & Iteration
- Searching, Min/Max & Reverse
- Insert, Delete by Index & Shift