Sequential search¶
Content summary
This lesson introduces the sequential search algorithm.
Idea¶
Imagine a deck of cards all face down. You need to find where one of the 3s is (any of the four 3s).
The natural way is to flip the cards one by one, starting from the top, until you see a 3.
We apply the same idea to an array:
We compare each element with the target value k, from the beginning to the end, and stop as soon as we find it.
Here’s how it works step by step:
How the sequential seach algorithm works
-
Go through the array from the first element to the last (
A[i]), and for each positioni:- If
A[i] == k, returni— that’s the index where the value was found.
- If
-
If we finish checking all elements and never found
k, return-1(meaning: not found).(
-1is a common convention for "not found" because array indices start at 0 — there are no negative indices.)
Terminology
Sequential search is also known as linear search.
Both terms can be used interchangeably. Internationally, linear search is the more common term. In Vietnamese textbooks, however, it is usually translated as sequential search (tìm kiếm tuần tự).
Flowchart¶
Visualization¶
Writing the program¶
1. Import the numpy library.
2. Write the function linear_search() to implement the sequential search algorithm.
The function takes two input parameters:
- The array
A - The target value
k
It returns:
- The index
iwherekis found, or -1ifkis not found.
3. Write the main program.
For simplicity in this example, we will skip asking the user to input the entire array. Instead, we create a fixed array in the code, and the user only needs to enter the value they want to search for.
Call the linear_search() function and store the result (the found index or -1) in a variable named found.
Use the variable found to print an appropriate message:
- If
foundis not-1, display that the value was found and show its position. - If
foundis-1, display that the value was not found.
4. Run the program above and enter 9. The output will be:
Run the program again and enter 6 as the value to search for. The output will be:
Note
If the value k appears multiple times in the array, the sequential search algorithm will return only the first occurrence (the one found earliest during the traversal).
Source code¶
The complete code is available at:
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| so sánh | compare |
| thuật toán tìm kiếm | search algorithm |
| tìm kiếm tuần tự | sequential search, linear search |
| tìm thấy, không tìm thấy | found, not found |