Master fundamental searching algorithms and their implementations in Java. Learn when to use different search strategies and understand their performance characteristics.
public class LinearSearch {
public static int linearSearch(T[] array, T target) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(target)) {
return i;
}
}
return -1;
}
// Generic linear search with custom comparator
public static int linearSearch(
T[] array,
T target,
Comparator super T> comparator) {
for (int i = 0; i < array.length; i++) {
if (comparator.compare(array[i], target) == 0) {
return i;
}
}
return -1;
}
}
public class BinarySearch {
public static > int binarySearch(T[] array, T target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int comparison = array[mid].compareTo(target);
if (comparison == 0) {
return mid;
} else if (comparison < 0) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// Recursive implementation
public static > int binarySearchRecursive(
T[] array, T target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
int comparison = array[mid].compareTo(target);
if (comparison == 0) {
return mid;
} else if (comparison < 0) {
return binarySearchRecursive(array, target, mid + 1, right);
} else {
return binarySearchRecursive(array, target, left, mid - 1);
}
}
}
For additional hands-on practice and detailed exercises on searching algorithms, check out our comprehensive guided project:
Practice implementing and using search algorithms:
Challenge yourself with these advanced problems:
Apply search algorithms to practical scenarios: