9.1Searching Basics and Linear Search
Covers IGNOU MCS-208 §9.0, 9.1, 9.2
To search is to find the record whose key matches a given value. The simplest method looks at every record in turn. This page defines the vocabulary and analyses that method.
Files, records and keys
A file (or table) is a collection of records, and each record is a collection of fields. A field used to identify records is a key. In a telephone directory, each record has the fields name and phone number; usually the name is the key, but a reverse directory would use the number as the key. A search takes an argument and finds the record whose key equals (a successful search) or reports that there is none (unsuccessful).
Linear search
It works on any array, sorted or not, and on linked lists.
Efficiency
| Case | Comparisons |
|---|---|
| Best (key at the first position) | 1 |
| Worst (key at the last position, or absent) | |
| Average, successful (each position equally likely) | |
| Unsuccessful |
So linear search is . For small or unsorted arrays, and for a single search, it is perfectly reasonable.
Key takeaways
- File → records → fields; the key identifies a record.
- Linear search: compare one by one, stop at the first match; works on unsorted data.
- Best 1, average (successful), worst and unsuccessful : .
- A sentinel saves one test per step.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a C function for linear search that returns the position of the key or −1, and give its best, average and worst number of comparisons.
Show worked answer
int linear_search(const int m[], int n, int el) {
for (int k = 0; k < n; k++)
if (m[k] == el) return k; /* stop at the first match */
return -1; /* unsuccessful */
}
Best case: 1 comparison (key at index 0). Worst case: (key last or absent). Average for a successful search with every position equally likely: . Order .