Sentinel Linear Search is an optimized variation of the linear search algorithm. It places the target element at the last position of the array temporarily, allowing the search loop to avoid checking the array boundary during each iteration.
- If the target is found before the last index, its index is returned.
- If the target is found only at the last index because of the sentinel, the original last element is checked.
- It works on unsorted arrays.
Linear Search in Java
Linear Search is a simple searching algorithm that checks each element of an array sequentially until the target element is found or the array ends.
import java.io.*;
// Driver Class
public class GFG {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
// Found the target element and return its index
if (arr[i] == target) {
return i;
}
}
// Target not found in the array
return -1;
}
// Main Function
public static void main(String[] args) {
int[] arr = { 4, 2, 7, 1, 9, 5 };
int target = 7;
int index = linearSearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
Output
Element found at index: 2
Sentinel Linear Search
Sentinel Linear Search is an optimized variation of Linear Search that uses a sentinel value to reduce the number of comparisons during the search.
import java.io.*;
// Driver Class
public class GFG {
public static int sentinelLinearSearch(int[] arr, int target) {
int n = arr.length;
// Store the last element
int last = arr[n - 1];
arr[n - 1] = target;
int i = 0;
while (arr[i] != target) {
i++;
}
arr[n - 1] = last;
if (i < n - 1 || last == target)
return i;
return -1;
}
// Main Function
public static void main(String[] args) {
int[] arr = { 4, 2, 7, 1, 9, 5 };
int target = 7;
int index = sentinelLinearSearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
Output
Element found at index: 2