Learn to implement and apply linear and binary search algorithms.
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
int[] numbers = {5, 12, 8, 130, 44};
System.out.println(linearSearch(numbers, 12)); // 1
System.out.println(linearSearch(numbers, 10)); // -1
public static int binarySearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (sortedArray[middle] == target) {
return middle;
}
if (sortedArray[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
int[] sortedNumbers = {1, 5, 8, 12, 20, 45, 67, 99};
System.out.println(binarySearch(sortedNumbers, 12)); // 3
System.out.println(binarySearch(sortedNumbers, 10)); // -1
public static int recursiveBinarySearch(int[] sortedArray, int target, int left, int right) {
if (left > right) {
return -1;
}
int middle = (left + right) / 2;
if (sortedArray[middle] == target) {
return middle;
}
if (sortedArray[middle] > target) {
return recursiveBinarySearch(sortedArray, target, left, middle - 1);
}
return recursiveBinarySearch(sortedArray, target, middle + 1, right);
}
int[] sortedNumbers = {1, 5, 8, 12, 20, 45, 67, 99};
System.out.println(recursiveBinarySearch(sortedNumbers, 12, 0, sortedNumbers.length - 1)); // 3
System.out.println(recursiveBinarySearch(sortedNumbers, 10, 0, sortedNumbers.length - 1)); // -1
Given a sorted array of integers and a target value, find the starting and ending position of the target value.
// Challenge: Find First and Last Position
public static int[] searchRange(int[] nums, int target) {
// Your code here
return new int[] {-1, -1};
}
int[] result1 = searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8); // Output: [3, 4]
int[] result2 = searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6); // Output: [-1, -1]
If you want more practice with search algorithms, check out these LeetCode problems: