Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Linear search: two ways


1. Linear search: two ways
This page looks at linear search.

The input is in multiple (two) parts so, in this case, two trailer loops are used, one after the other.

Note: Integers are used but larger structure types could be used.

2. Goal
The goal of the program is to read in a sequence of integers - the first list.

Then, another sequence of integers is read in and, for each, it is determined if that integer is in the first list. If it is, then the position in the list is displayed.

For example purposes, input, processing, and output are not fully separated.

3. Example input
Here is some example input, with "..." for omitted parts and the trailer values colorized.
12 23 ... 78 89 -1 34 ... 67 -1


4. Data
The data structures are as follows.


5. Input first list


The second input of integers is similar.

6. Result
The result of two ways of searching use the same code for the output (not abstracted in the program since we would only be using one way anyway).


7. Search using guard
Here is the search using a compound condition as a (code) guard. Remember, the conjunction condition is short-circuit evaluation.

A "guard" is a code condition (e.g., Boolean) that guards code from going too far or doing something not to be done.

8. Point of view
Note: The value zero (0) can be used to indicate not found since the list is one-based. However, if the list is zero-based, then the not found value might be negative one (-1).

9. Search using sentinel
Here is the search using a (data) sentinel at position 0 in the array (since that position is not being used).

A "sentinel" is a data value that acts to protect code from going too far or doing something not to be done.

10. Complete program
Here is the C code.


11. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.


12. Abstraction
The next step is to abstract the search functionality into a function.

13. Search abstraction using  guard
Here is the abstracted search code that uses a code guard.


14. Search abstraction using sentinel
Here is the abstracted search code that uses a data sentinel.


15. Complete program
Here is the C code.


16. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.


17. End of page

18. Multiple choice questions for this page