Information Technology Topic
Linear Search
- Read notes
- Flashcards
- Quiz
- Confident
Study focus - 3 things
- A linear search checks the items one at a time from the first, comparing each with the target, and stops when the target is found or the end of the list is reached; the list does not have to be in order
- A found flag (true or false) and a position variable record the result, and the program tests found after the loop because the loop can end in two ways
- With n items the best case is 1 comparison, the worst case (target last or absent) is n, and on average about half the list is checked when the target is present
Section 1Searching a list
Searching means looking through a list for one particular value, called the target. You do it all the time: looking for your name on a class list, or for one price on a shelf label. A linear search (also called a sequential search) checks the items one at a time, starting at the first. Here is the plan in plain steps: 1. Start at the first item. 2. Compare the item with the target. 3. If they are the same, record the position and stop. 4. If not, move on to the next item. 5. If you run out of items, the target is not in the list. As a flowchart, step 2 is a decision box: Yes leads to recording the position, and No loops back to the next item. Here's the trick: the search only needs two things from the list, to look at one item at a time and to know where the list ends. It does not need the list to be in order.
Section 2Remembering the answer: a found flag and a position
A search loop can end in two different ways: the target was found, or the items ran out. After the loop the program must know which happened. So it keeps two extra variables: - found is a flag. It starts as false and is set to true when the target is matched. In Pascal-style code its type is boolean. - position holds the index where the target was found. It starts at 0, which is not a real position, so 0 means that nothing has been found yet. A third variable, index, walks along the list starting at 1. The loop keeps going while there are items left AND found is still false. When found becomes true, the loop stops at once.
Section 3The Pascal-style program
This Pascal-style program searches the five marks 62, 75, 48, 90 and 55 for a target typed in. program FindMark; var marks : array[1..5] of integer; target : integer; index : integer; position : integer; found : boolean; begin marks[1] := 62; marks[2] := 75; marks[3] := 48; marks[4] := 90; marks[5] := 55; readln(target); found := false; position := 0; index := 1; while (index <= 5) and (found = false) do begin if marks[index] = target then begin found := true; position := index end else index := index + 1 end; if found = true then writeln('Found at position ', position) else writeln('Not found') end. In this Pascal-style version a decision sits inside the loop: each pass makes exactly one comparison, marks[index] = target. The plan in numbered steps above is flat, with no nesting. A plain for loop would keep comparing after a match, so this program uses a while loop that can stop as soon as found is true. Notice there is no semicolon before else, and each comparison in the loop condition has its own brackets. In Pascal, and is worked out before = and <=, so (index <= 5) and (found = false) needs those brackets.
Section 4Tracing a successful search
Run the program with the target 48. Write down index, found and position at the start and after each pass. Start: index 1, found false, position 0 Pass 1: marks[1] is 62, not 48, so index becomes 2 Pass 2: marks[2] is 75, not 48, so index becomes 3 Pass 3: marks[3] is 48, a match, so found becomes true and position becomes 3 Then the test found = false fails, so the loop ends. The program displays Found at position 3. That took 3 comparisons. Index stayed at 3 on the last pass, because the else part, which moves index on, was not used. Target 90 is the fourth item, so it takes 4 comparisons and shows Found at position 4. Target 55 is the last item, so it takes 5.
Section 5When the target is not in the list
Now run the program with the target 70, which is not in the list. Passes 1 to 5 compare marks[1] to marks[5] with 70, and none matches, so index moves 2, 3, 4, 5 and finally 6. Then the test index <= 5 fails, because 6 is not less than or equal to 5, and the loop ends. found is still false and position is still 0. The final decision takes the else part and displays Not found. That took 5 comparisons, one for every item. A search that fails always has to look at every item before it can be sure. Watch out: the loop limit must match the array. If the condition said index <= 6, the program would try marks[6] on the sixth pass, which does not exist, and (with range checking on) stop with a run-time error.
Section 6How many comparisons?
The work done by a linear search depends on where the target is. Best case: the target is the first item, so 1 comparison. Worst case: the target is the last item, or is not in the list at all, so every item is checked. With n items that is n comparisons. Average case: when the target is in the list, about half the items are checked, about n / 2. If the list grows from 100 to 200 items, the worst case doubles from 100 comparisons to 200, and the average rises from about 50 to about 100. If the target appears twice, the search stops at the first match, so it reports the earlier position. Easy to mix up: the position is where the target is in the list. The number of comparisons is how much work the search did. For a match at position 3 they happen to be equal, because the search starts at 1 and does not skip anything.
Section 7Common slips in a search program
- Forgetting to move on. If the Pascal-style line index := index + 1 is missing, the program compares the first item again and again for ever. - Setting found to true before the search, or never setting it back to false when a new search starts, so the result is wrong. - Going past the end of the list, for example index <= 6 for five items. - Forgetting to test found after the loop. The program then cannot tell Found from Not found. - Leaving out the brackets round the two comparisons in the loop condition, which Pascal does not accept. Here's the trick: trace the program twice, once with a target that is in the list and once with a target that is not. Most mistakes show up in one of those two traces.
Examples
The list marks holds 62, 75, 48, 90 and 55 in positions 1 to 5. The FindMark program in the notes is run with the target 90. (a) Show index, found and position at the start and after each pass. (b) State the line displayed. (c) State how many comparisons were made. (d) State why the loop stops without checking marks[5].
(a) Start: index 1, found false, position 0. Pass 1: 62 is not 90, so index 2. Pass 2: 75 is not 90, so index 3. Pass 3: 48 is not 90, so index 4. Pass 4: 90 matches, so found true, position 4, index stays 4. (b) Found at position 4 (c) 4 comparisons, one for each pass. (d) After pass 4 the value of found is true, so the test found = false is FALSE and the loop ends. marks[5] is never needed because the target has already been found.
A hardware shop in Mandeville keeps five item codes in an array. The FindMark program is changed only by renaming the array to codes, by filling it with codes[1] := 301; codes[2] := 255; codes[3] := 412; codes[4] := 187; codes[5] := 266; and by comparing codes[index] with target. (a) The target typed is 187. State the line displayed and the number of comparisons. (b) The target typed is 500. State the line displayed, the final value of index and the number of comparisons. (c) State the best case and the worst case for this list of 5 codes. (d) The shop grows to 200 codes. State the worst case and roughly the average case when the code is in the list.
(a) 301, 255 and 412 do not match, and 187 matches on the fourth comparison. The line displayed is Found at position 4, after 4 comparisons. (b) None of the five codes is 500, so all 5 comparisons are made and index ends at 6. The line displayed is Not found, because found is still false. (c) Best case: the target is 301, the first code, so 1 comparison. Worst case: the target is 266 or is not in the list, so 5 comparisons. (d) The worst case is 200 comparisons. When the code is in the list, the average is about half of 200, which is about 100 comparisons.
Now let's water it
Session runs notes to flashcards to quiz back-to-back.
Where this comes from
- CSEC Information Technology Syllabus (CXC 30/G/SYLL 08, revised 2000, 2008, 2013) · Caribbean Examinations Council (CXC) · Section 3, Specific Objective 9 · Syllabus scope
- Dictionary of Algorithms and Data Structures (P. E. Black, ed.), entries algorithm and linear search · National Institute of Standards and Technology (NIST) · Page linearSearch, Dictionary of Algorithms and Data Structures (search an array or list by checking the items one at a time; average case about n/2 checks when the item is present), checked against (https://xlinux.nist.gov/dads/HTML/linearSearch.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 3, Static arrays (3.3.1; array[low..high] of type, index in square brackets, index outside the range is a run-time error), checked against (https://www.freepascal.org/docs-html/ref/refsu14.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 13, The while..do statement (13.2.7), checked against (https://www.freepascal.org/docs-html/ref/refsu61.html) · Facts
- Free Pascal Reference guide v3.2.2 (16.1 Programs, 16.5 Blocks and the language pages in the facts sheet), RTL entries Write, Writeln, ReadLn, and User's guide 3.2 and Appendix D · Free Pascal team · Chapter 12, Boolean operators and relational operators (12.8.3 and 12.8.7; and, = and <=), checked against (https://www.freepascal.org/docs-html/ref/refsu46.html) and (https://www.freepascal.org/docs-html/ref/refsu50.html) · Facts