Sequential Search (also called Linear Search) is a classic brute-force algorithm: it makes no assumptions about the order of the data and
exhaustively tests every element. Starting at index 0, it compares the value of each element to the target value; if a match is found,
it immediately returns the index of that element. Otherwise, it moves to the next element, continuing until either the target is located or the end of the array is reached at which point it returns -1.
Because it “tries every possibility,” you are guaranteed to find
the target if it is present with no more than n comparisons.
More formally, the algorithm works as follows:
i = 0.A[i] with target.i.i.i==n (end of the array), return -1. Otherwise, repeat from step 2.public int sequentialSearch(int[] A, int target) {
for (int i = 0; i < A.length; i++) {
if (A[i] == target) {
return i;
}
}
return -1;
}
int sequentialSearch(int A[], int n, int target) {
for (int i = 0; i < n; i++) {
if (A[i] == target) {
return i;
}
}
return -1;
}
def sequential_search(A, target):
for i, value in enumerate(A):
if value == target:
return i
return -1
Time Complexity: We count the number of element-to-target comparisons as our cost metric. If the target is found at position k, then k comparisons were executed since it compare the target with each of the first k elements until it found it. If the target is not present, then it compared the target with every element of the array, so it did m comparisons.
From this we can see:
Space Complexity: The iterative sequential search uses only a fixed number of additional variables:
The loop index i, the space for the target, and the return value.
and a few constant‐size temporaries (if any). Thus, the space complexity is O(1).
O(1), when the target is at index 0.O(n), when the target is at the last position or not present.O(1), since it only uses a constant amount of extra space.