Standard Methods of Solution
Standard Methods of Solution
solution
By M Dzinzi
Standard methods used in
algorithms
• Totalling
• Counting
• Finding maximum, minimum, and average (mean) values
• Searching using linear search
• Sorting using bubble sort
Totalling and counting
• Totaling – Used with repetition, to keep the total updated. E.g.
BillTotal BillTotal + ProductCost
• Counting – Used with repetition to increment the counter by 1, each
time the loop is repeated. E.g.
NumItems NumItems + 1
Counting
PassCount ← 0
FOR Counter ← 1 TO ClassSize
INPUT StudentMark
IF StudentMark > 50
THEN
PassCount ← PassCount + 1
NEXT Counter
Count ← Count + 1
Maximum
MaximumMark ← 0
MinimumMark ← 100
FOR Counter ← 1 TO ClassSize
IF StudentMark[Counter] > MaximumMark
THEN
MaximumMark ← StudentMark[Counter]
ENDIF
IF StudentMark[Counter] < MinimumMark
THEN
MinimumMark ← StudentMark[Counter]
ENDIF
NEXT Counter
• If the largest and smallest values are not known, an alternative method is to set the
maximum and minimum values to the first item in the list.
MaximumMark ← StudentMark[1]
MinimumMark ← StudentMark[1]
FOR Counter ← 2 TO ClassSize
IF StudentMark[Counter] > MaximumMark
THEN
MaximumMark ← StudentMark[Counter]
ENDIF
IF StudentMark[Counter] < MinimumMark
THEN
MinimumMark ← StudentMark[Counter]
ENDIF
NEXT Counter
Average (mean)
Total ← 0
FOR Counter ← 1 TO ClassSize
Total ← Total + StudentMark[Counter]
NEXT Counter
Average ← Total / ClassSize
Linear Search
• A search is used to check if a value is stored in a list, performed by
systematically working through the list
• This is called a linear search, which inspects each item in a list in turn
to see if the item matches the value searched for.
• For example, searching for a name in a class list of student names,
where all the names stored are different items in the list.
9
Linear search
Search
The search
Then it continues
begins with
The criteria in moves until a match
the first
which the item to the is found or
item and
has to be second the end of
checks
searched is set item, the list is
whether a
up. and so reached with
match is
on. no match
found.
found.
OUTPUT "Please enter name to find "
INPUT Name
Found ← FALSE
Counter ← 1
REPEAT
IF Name = StudentName[Counter]
THEN
Found ← TRUE
ELSE
Counter ← Counter + 1
ENDIF
UNTIL Found OR Counter > ClassSize
IF Found
THEN
OUTPUT Name, " found at position ",
Counter, " in the list."
ELSE
OUTPUT Name, " not found."
ENDIF
Bubble sort
• Each element is compared with the next element and swapped if the
elements are in the wrong order, starting from the first element and
finishing with next-to-last element
• Once it reaches the end of the list, we can be sure that the last element is
now in the correct place.
• Each element in the list is compared again apart from the last one
because we know the final element is in the correct place.
• This continues to repeat until there is only one element left to check or no
swaps are made.
13