Sequential Search
Sequential Search scans from one end, comparing keys one by one until the target is found or the scan ends. Works for unordered or ordered linear lists; best for small data or low efficiency requirements.
Click "Step forward" to watch the algorithm state change.
- Small linear lists
- Unordered tables, or whenever the efficiency requirement is low
Pseudo-code:
for i = 0 to n-1:
if A[i] == x:
return i // found
default:
return -1 // not found
In a sequential table we can place a sentinel (the target value stored at index ). The bounds check then disappears from every round of the loop, which speeds the search up:
// Sequential search (sentinel version); elements are stored from index 1 on.
int SeqSearch(int A[], int n, int key) {
A[0] = key; // the sentinel
int i;
for (i = n; A[i] != key; i--); // compare backwards, no bounds check needed
return i; // i == 0 means "not found"
}
Assume every element of the table is equally likely to be searched for, with probability .
Successful search: the comparison counts are , so the average number of comparisons is
Failed search: all elements are compared and then the sentinel is compared as well, giving comparisons in total:
- Best: (first element matches)
- Worst: (last or absent)
- Average:
Exercise 1
Given , use sequential search to find .
Approach: Compare one element after another until the key is hit.
Steps:
- Compare , which is not
- Compare , which is not
- Compare , which is not
- Compare and the key is found
Answer: Index .
Exercise 2
Which structures can use sequential search, and what is its average time complexity?
Approach: The scenarios and the complexity.
Steps:
- Applies to unordered or ordered linear lists
- Average time complexity
Answer: Linear lists, with an average of .
2021·408
In a sequential list of length , search for : on success swap it with its successor; on failure insert it at the end of the list. Write the algorithm and analyse the average time complexity.
Approach: Sequential search plus swap or insert, then count the average comparisons.
Steps:
- Search for sequentially from the head of the list
- Once it is found, swap it with its successor
- If it is not found, insert it at the end of the list
- The average number of comparisons is , and a failed search needs comparisons
- Average time complexity
Answer: As shown above, on average.
