Linear search

array data structures

Let's populate an array with random integers:

0123456

As you can see we can search for an item in an array data structure. We start at the first element and step through the array looking for the item.

This is known as linear search and here is a classic linear search algorithm:

DECLARE nums : ARRAY[1:10] OF INTEGER

DECLARE searchItem : INTEGER

DECLARE found : BOOLEAN

found ← FALSE

INPUT searchItem

FOR i ← 1 TO LENGTH(numArray)

IF numArr[i] = searchItem THEN

found ← TRUE

END IF

END FOR

IF found = TRUE

THEN

OUTPUT "Item found in array!"

ELSE

OUTPUT "Item not in the array"

END IF

Well! It works! And it works well.

For this sort array, time is not a factor.

However, for a much longer array, time becomes a consideration and this is an inefficient algorithm as the search process continues even after the item has been found.

   Practical Activity #1 - Design + Corrective maintenance

Code the above algorithm in your chosen high-level programming language.

As you test your design, perform corrective maintenance to fix any:

  • syntax errors
  • logic errors
  • run-time errors

Save your solution in your evidence document.

   Practical Activity #2 - Adaptive maintenance

Design or research an algorithm that will find an item in an array and stop processing once the array has been found.

You may use break to help you do this in your practical coding.

However, for maximum credit, can you figure it out without using break.

Save your solution in your evidence document.

   Pseudocode activity

Translate your solution into pseudocode.

Save your solution in your evidence document.


   

This unit requires you to create an evidence document.

Tags

data type INTEGER pseudocode ← program code assign STRING CHAR linear search BOOLEAN DECLARE variable


Feelings

How do you feel right now?