This document discusses several standard algorithms:
1) Linear search searches an array to find a value and returns its position or a message if not found.
2) An improved linear search algorithm stops searching once the item is found and returns a message if not found.
3) Count occurrences counts how many times a value appears in an array.
4) Finding the maximum/minimum value in an array uses comparisons to update the running maximum/minimum value found.
2. LINEAR SEARCH
• Linear search searches an array for a specific value
• If the value is found it will return its position in the array
• If the value is not found it will return a message to say so
3. LINEAR SEARCH: SIMPLE
Pseudocode:
INITIALISE colours array
ASK user FOR search_item
REPEAT with position FOR number of items in array
IF colours[position] = search_item THEN
DISPLAY “Search item found in position ” & position
5. LINEAR SEARCH: SIMPLE
Issues:
1. Continues through loop when item found (inefficient)
2. No message if item not found
3. Displays array position rather than actual position
1st item = position 0
2nd item = position 1
etc
4. Loop fixed - 6 times
6. LINEAR SEARCH: IMPROVED
INITIALISE colours array
SET found TO false
SET position TO 0
ASK user FOR search_item
WHILE position < array length AND found is false DO
IF colours[position] = search_item THEN
SET found TO true
ELSE
ADD 1 TO position
IF found is true THEN
DISPLAY ‘Colour found in position’ & position + 1
ELSE
DISPLAY ‘Colour not found’
8. COUNT OCCURRENCES
• Count occurrences will count the number of times a specific value
appears in an array
• For example:
[‘A’, ‘B’, ‘C’, ‘C’, ‘A’, ‘A’, ‘B’]
The letter A appears 3 times in the array
9. COUNT OCCURRENCES
Pseudocode:
INITIALISE colours array
SET occurrences to 0
ASK user FOR search_item
REPEAT WITH counter FOR array length
IF colours[counter] = search_item THEN
ADD 1 TO occurrences
DISPLAY occurrences
11. FIND MAXIMUM / MINIMUM
• Find maximum will return the largest value in a list
• Find minimum will return the smallest value in a list
• Algorithms are almost identical, the main difference is in the IF
statement:
• > comparison (maximum)
• < comparison (minimum)
12. FIND MAXIMUM
Pseudocode:
INITIALISE heights array
SET maximum TO first array element
REPEAT WITH counter FOR array length
IF heights[counter] > maximum THEN
SET maximum TO heights[counter]
DISPLAY maximum
14. FIND MINIMUM
Pseudocode:
INITIALISE heights array
SET minimum TO first array element
REPEAT WITH counter FOR array length
IF heights[counter] < minimum THEN
SET minimum TO heights[counter]
DISPLAY minimum