Chapter 6 Algorithm and Data Structures
Chapter 6 Algorithm and Data Structures
Objectives
Learners should be able to:
. Analyse algorithms for a given situation
. Formulate trace tables for given algorithms
. Design algorithms for a given situation
. Demonstrate familiarity with standard algorithms
. Demonstrate familiarity with control structures
. Use standard algorithms to solve problems
. Distinguish between dynamic and static data structures
Algorithm Design
Introduction
The thrust of algorithm design is on solving problems which manifests themselves in every facet of lil
yet in different domains. Problem solving is a skill which all ofus should try to embrace and practirr
The idea behind problem solving is critical thinking which demands a great deal of cognitive coryc
tences,
Task
Dear reader, study the following problems and offer some solutions for each scenario.
Problem A
The missionaries and cannibals' problem
Once upon a time there were three missionaries and three cannibals who were all supposed to crocs.
river safely using a boat which can carry at most two people, under given constraints. For both riw
banks, if there are missionaries present on the bank, they cannot bC outnumbered by cannibals (i
they were, the cannibals would eat the missionaries). The boat cannot cross the river by itselfwith u
people on board. In a separate constraint/variation, one ofthe cannibals has only one arm and canoo
row.
Problem B
Woli goat and cabbage problem
A farmer wants to cross a river and take with him a wolf, a goat, and a cabbage. There is a boa thl
can fit himself plus either the wol( the goat, or the cabbage. Ifthe wolf and the goat are alone on o
shore, the wolf will eat the goat. Ifthe goat and the cabbage are alone on the shore, the goat will ear rb-
cabbage. How can the farmer bring the wolf, the goat, and the cabbage across the river?
Algorithm
An algorithm is a collection of a finite number of well-defined and ordered steps which wh- thq
2t3
are executed solve the intended problem. Further, an algorithm is an unambiguous finite sequl
procedures
steps that can be carried out to perform a task. It can also be defined as step by step
deine a set of instructions to be executed in a certain order to solve a problem. Algorithms
written in any language but generally English is used'
language. Hor'r
Note: Algorithms are never written/designed to supPorta Particular programming
cor
all high-ievel programming languages share basic code constructs like repetition/iteration
structres and selection control stru;tures. These common control structures can be
used to wril
algorithm. For us to design a problem solution, we should know the Problem domain'
lvell-dei
Tli"refor", algorithm writing is a process and is executed-after the problem domain_is
*d *.U-uni"r.tood. Algorithnis can be presented in the form of pseudocodes, flor,vcharts, stnrd
should be desil
;4.;r and descriptiois which will be covered in this book. Good algorithms
a good hati
witf, meaningfrrl iclentifiers; variables and constants. Learners sho'ld also develop
using trace tiles when dry running algorithms and even programs'
Comments maybe used to e4r
varial
certin parts of the algorithm. fJfoiter an aPPreciation oi the usefulness of identifiers'
.orrrt*tr, comments and trace tables, let us discuss each of them below'
Identifier
a variable or constar
An identifier is a name given to a variable, constant or subroutine. Assigning
wi
identifier name means that it can be easily referenced from any Part ofthe algorithm/program
its scope and it helps to make the algorithm/program more
readable'
Variable
of a Program'
A variable is a memory location whose value can change during the execution
Initialising-a variables
usually set the value <
Initialising variable means setting it to a starter value_. Initialisation will
integer to*0 or I and a string to
gipty t-). The initial values assigned to-variables depends or
clear memory of any < -
froff.- at hand and th" prJgrum-.r's discretion. Initialising is done to
possible value that may affect our result'
Constant
and does not ch
A constant is a memory location whose value is set when the program initialises
2t4
during the program's execution.
More details on variables, constants and subroutines are dealt with in Chapter 7 ofthis book.
Trace tables
A trace table is a technique used by programmers to track the values of variables as they change
throughout the running of an algorithm/program. The trace table is also used to test algorithms, in
order to make sure that no logical errors occur whilst the algorithm is being processed. Trace tables
are useful when a program is not producing the desired result. A dry run performed using a tracc
table is one way of checking and troubleshooting for errors in the algorithm or progr.rm code. Dry
run//desk checking means executing an algorithm mentally by following the logic in the algorithm-
Therefore, a trace table is used by a programmer to help simulate the running of a program. When
dry running an algorithm, the programmer traces each line ofcode with their finger and record thc
values in a trace table that includes the line number ofthe program. Thus, dry running involves using
trace tables to manually run an algorithm in order to determine if it is logically correct. All-variablc
names are written column wise and at each step/loop the values ofvariables are checked and wricco I
below the respective variable. When there is no change in the contents ofa variable, there is no necd
to record the same contents ofthat variable,
The following algorithm is designed to retain the maximum value from a given list of numbers.
Start
'Initialisation part
MaxElement = -l
Set count = 0
While count < 5
Input number
If number > MaxElement Then
MaxElement = number
End if
Increment count by I
End While
Output MaxElement
Stop
The following numbers are given for testing the algorithm: 9;3; 5; l0;7
9 9
I J
2 5
3 l0 l0
4 7
2t5
Trace table is a way oftracking the values ofvariables while testing the algorithm/Program'
Comments
These are brief explanatory notes added to code for the benefit ofthose reading it. Comments are the
only way to capture the intent of the algorithm/code at the time of writing. Comments provides clarity
on such things as the purpose ofthe algorithm and how parts of it works. These are statements which
provide essential documentation for anyone who wants to know such things as:
. Thepurposeofthealgorithm/pseudocode/program
. How particular sections ofthe algorithm works
. Use ofcertain variables in the algorithm/program
. The author ofthe algorithm/program
The algorithm designers should always provide comments to enhance the understanding of the
algorithm by other people, where clarity is lacking. Clarification comments are intended for anyone
(including your future self) who may need to maintain, refactor, or extend your code. However, after
all have been said, a good algorithm, pseudocode or program is self-documenting. Indentations are
also useftrl as one can clearly see at a glance the structure of control structures such as selection and
iteration.
Imports System.Console
Module Module I
Sub Main0 'program by Mungazi Mungazi
'Display twin prime numbers between 10 and 1000
Dim prime(496) As Integer
Dim y As Integer = 0, x As Integer, diff As Integer
Forx= ll To 1000Step2
IfxMod 2 = 0 OrxMod 3 = 0 OrxMod 5=0 OrxMod 7 = 0 Then
'x mod 2 = 0 has no effecl on lhis particular code since x = 11
'is the starling ralue and there is the Slep 2 increment
Else
While y < 496 '496 is usetl to store all the Prine numbers itt the array
'array to store prime nunbers between l0 atd 1000
Prime(Y) = 1
y+= I
ExitWhile 'force loop to terminate before executirtg ttt completiolr
End While
End If
Next
Forx=0To495
If prime(x) And prime(x + 1) Then
diff= prime(x + l) - prime(x)
If diff= 2 Then
2r6
Writeline(prime(x) & " And " &prime(x + l))
End If
Else
Exit For 'Jitrre loop to stop ul reduce processttr overhends
'there ore only 227 prine
nuntbers from t I to 1000
ind only 70 twin prime numbers, the loop runs.for 127 tines and stop
'instead of 495 times dictated h1, rhe loop
End If
Next
ReadKey0
End Sub
End Module
Control structures
Algorithms and computer Programs execute statements one line after the next, unless there is a
command that instructs the algorithm/progr.rm to jump backwards or forwards to an alternative
line. In a Program or an algorithm, a control structure determines the order in which
statements
are executed. Control structwes form the building blocks of a structured program.
There are threc
building blocks orProgram corstructs used to write algorithms and subsequentlistructured prograns
Learners should familiarise themselves with the control structures and Le flexible in
using Gm t
designing algorithms. There are a number of programing control structures available that can
be uscd
when writing algorithms and pseudocodes. In this book the three basic/common control structurc
used in algorithm design and in programming are going to be discussed and these are
sequence,
selection and iteration.
2t7
I
J
f--*--;;;;-l
f I
I
t
f k;;t-__-l
Begin
Set Sum to zero
Input first number; numberl
Input second number; number2
Sum=numberl+number2
Display Sum
End
Flowchart
218
lnput numberl
lnput number2
Output Sum
End
219
\
Note that Ifstructure expressed in a single line is not terminated by End If. This
version ofthe If
structure is seldom used.
. If (condition) Then
Action
End If
. If (condition) Then
Action I
Else
Action 2
End If
. Block If structure
If (condition) Then
Action I
Elself (condition) Then
Action 2
Else
Action 3
End If
. Nested If structure
If (condition) Then
If (condition) Then
Action I
Else
Action 2
End If
Else
End If
If (condition) Then
Action I
Else
If (condition) Then
Action 2
Else
Action 3
End if
End If
Basic flowchart for IF Structure
Example I
Write an algorithm which adds numbers when numberl is negative, otherwise subtract number2
from numberl
221
Begin
Set sum to zero
Difference = 0
Enter numberl
Enter number2
If numberl < 0 Then
sum=numberl+number2
Display sum
Else
Difference = numberl- number2
Display Difference
End if
End
Example 2
Design an algorithm to add any two Positive numbers.
Begin
Set sum to zero
Enter numberl
Enter number2
If numberl > 0 Then
If number2 > 0 Then
sum=numberl+number2
Display sum
End if
Else
Display error message
End if
End
Case structure
.
A case or switch statement is a type ofselection control mechanism used to allow the value ol
variable or expression to change the control flow of program execution via a multiway branc
.
This selection method is used if there are more than two possible outcomes to a test.
.
It is a conditional control structure that allows a selection to be made between several sets
program statements, the choice is dependent on the value of some expression
.
The case statement is a more general structure than the IF...THEN...ELSE statement whi
allows a choice between only two sets of statements
.
It is a conditional block used as a method of shortening a long set of IF. . .THEN.. .ELSE stat
ments
222
Basic flowchart for Case structure
continues
223
While . .. End While Structure/Pre-Test repetition
It consists of:
. The word While
. A TRUE or FALSE condition
. One or more statements to be repeatedly executed (known as the loop body)
. The words End While, indicating the end of the looping structure
The statements in the loop body are indented so that the span ofthe structure ofthe loop is seen at a
glance. When the While loop is encountered in an algorithm or Program, the following actions take
place
The while loop executes the loop body when the sit condition is True, until it becomes False. Ifthe
condition is False from the beginning, the loop body is not be executed at all'
224
Example
Write an algorithm to convert given centigrade temperatures to Fahrenheit.
Hint:F=32+(9*C/5)
Begin
Print "Enter 0 to terminate the loop,
Prompt user to enter C
While C< > 0
F =32 + (9*Ct5)
Print C and F
Prompt user to enter C
End While
End
rhe loop body is repeatedly executed as long as the condition is FALSE. when the condition be-
comes TRUE, execution ofthe loop is stopped.
225
Execite statement up to Until
l0 l0 50
0
226
table gives the comparison between
il:,fi*;t" rhe while .. . End while loop and the Repeat ...
The standard algorithms can be represented using the following algorithmic tools; descriptions,
pseudocodes or fl owcharts.
Descriptions
in order to complete
These are general statements that are followed a specific task. They are not gov-
erned by any programming language. An example is as follows:
Start
Enter temperature in oC
Store the value in box C
Calculate the equivalent temperature in oF
Store the value in box F
Print the value ofbox C and F
Stop
Pseudocode
Pseudocode is a simplified form of programming code that uses common progr.rmming keywords, but
does not use the strict syntax of any programming language. These are English-like statements, closer
to programming language that indicates steps followed in performihg a specific task. Pseudocodr
essentially is English statements with some defined rules of structure and some keywords that make it
appear a bit like a program code. Pseudocodes are a means ofexpressing algorithms without worryinl
about the syntax ofthe programming language, There are no strict rules on howpseudocode statementt
should be written. Indentations are very important in writing pseudocodes since they clearly indicatt
the extent of loops and conditional statements. Comments can be made to explain some pseudocodr
statements. The fact that pseudocodes are independent of any programming language need to br
always remembered.
An example is as follows:
Begin
Enter centigrade temperature, C
IfC =O, then End
228
Set F to 32 + (9C15)
Print C and F
End
Start
Initialise Sum to zero ll Set Sum to zero // Sum = 0
Input numberl
Input number2
Sum=numberl+number2
Print Surn
Stop
Practice questions
l Design algorithms which calculate the perimeter for the following shapes
a. Triangle
b. Rectangle
c. Trapezium
d. 8-sided polygon
2. Draw the flowcharts for each algorithm designed in question I above.
Example
Start
Set Diference to zero
Enter numberl
Enter number2
Difference = numberl - number2
Print Difference
Stop
Assuming that the value entered for numberl and number2 are 7 and 5 respectively, the trace table is
given below
229
Standard algorithms for multiplication
Example
Start
Set Product to I
Enter numberl
Enter number2
Product = numberl * number2
Print Product
Stop
Practice questions
L Write separate algorithms which calculate the areas of the following plane shapes
a. Triangle
b. Rectangle
c. Trapezium
d. Circle
Example
Start
Set Quotient to zero
Enter numberl
Enter number2
Ifnumber2=0then
Print error message
Else
Quotient = numberl / number2
Print Quotient
End if
Stop
All control structures can be used to solve arithmetic problems.
230
Example questions
I write an algorithm which calculates the sum of two numbers when the second
than the first number or otherwise subtract second number is greater
number from the first number.
2 A class of ten students wrote a test which was marked promptry bytt t.u.t.r.
which calculates the average mark for the l0 marks w.ii" an algorithm
"
ibtained from the r0 students.
Example I
Start
Set Total to zero
Set Difference to zero
Enter numberl
Enter number2
If number2 > numberl then
Total = numberl + number2
Print Total
Else
Difference = numberl - number2
Print Difference
End if
Stop
Let us dry run the algorithm given that numberl = 7 and number2 = 5
rhe trace table is as follows
Example 2
Start
Set Average to zero
Set Sum to zero
Set count to zero
While count < l0
Input mark
If mark < 0 or mark > 100 then
print 'Enter marks from 0 to 100
only,
Else
Sum=Sum+mark
count = count + I // increment count by I
End if
End while
Average=Sum/count
Output Average
Stop
23r
Let us dry run the algorithm assuming that the following marks were obtained by the ten students,
26, 58, 89, trz,80, 64,56, -83, 91, 68,70,78
The numbers I l2 and -83 were erroneous keyed in for reasons not worth disclosing here
Trace table
count condition mark Sum Average
0 0 0
0 True 26 25
I True 58 a4
2 True 89 t73
3 True t12
3 True 80 253
4 True 64 3t7
5 True 56 373
6 True -83
6 True 9L 464
7 True 68 532
8 True 70 602
9 True 78 680
l0 False 68
Practice questions
l.
Using any loop ofyour choice, write an algorithm which accepts and displays I I subjects offerer
at a private college.
2. Write an algorithm that displays all prime numbers between 0 and 100 exclusively.
3. Write an algorithm that calculates and display the average of all prime numbers in the range I
to 100.
4. Write an algorithm that displays dl twin prime numbers in the range 0 to 1000. Examples o
twin prime numbers are 3 and 5, ll and 13, 17 and 19 and so forth.
5. Write an algorithm which calculates and displays the sum and average of all odd number
between 200 and 1000 inclusively.
6. Given t}le following list of numbers; 23,13, -21,36, -14, 17, -2, l8 and -69. Write an algorithn
which calculates and displays the average of all the negative numbers and that of all positiu
numbers that are greater than 19.
7. Write an algorithm which displays the largest, average and smallest mark for a class of n student
for a test that was marked out of 100.
8. Write an algorithm which accepts any number of integers and determines how many are negatir
and how are positive.
Sorting Algorithms
Sorting is a fundamental process in working with data and deserves close study. A sorting algorithm
a method for reorganising a large number of items into a specific order, such as alphabetical,
232
to-lowestvalueorshortest-to-longest.distance.Sortingalgorithmstakelistsofitemsasinputdata,
perform specific operations on those lists and deliver irdJred
arrays as output. e-sorting operation
is nothing more than a series of comparisons. Sorting algorithms
.o-p"re'it"rns
"niof any type is lfa
swap th.m
necessary. All the information needed by a sorting algo.ith-
to op.r"i. on an item
function that compares two objects of the same cu-stoir type. Sorting
algorithms are a concept that
every comPetitive Programmer mus^t know sorting algorithms
can be useJ for collections of numbers,
strings, characters, or a structure of any of these typa. an algorithm
that takes an unsorted list and
uses a comparison function to put the list into sorted order
is aiorting algorithm. A number of sortiag
techniques are available that include merge sort, selection sort,
heap sJrt but this book will discuss
bubble sort and quick sort
Bubble Sort
Bubble sort is a sorting method where adjacent pairs of values
in a list or array are compared and
ty"pp:d positions if they exist in the wrong order. Bubble sort works by ..-p;;g .ach element
of the list with the element next to and swapping them if required.
it
that works by repeatedly stepping through
It i, ; ili;.";i'g
th;hsito be sorted, comparing *.i
pJ, "tgorirh;
them if they are in the wrong order. With each pass, the largest ofthe -aswapping
list is bubbled to the end of the
list whereas the smaller values sink to the bottom. This b rhf,hng is
h*dil t;;;n-er roR bop as
bubble sort uses two nested loops, complete bubble roit p"r, r. th. Jr,.l" *ii.r, the biggest
element in the list or .rray |
{ngle
bybblgd to its coirect position. The pass through trr. ilrt i, repeated
f
until no swaps are needed, which indicates that the list is sorted. It is a very
slo:w way or sorting data
especially with large arrays of elements and rarely used in industry.
Bubble sort is usually used to sort a small number of items (i.e.
iess than 50). To sort an array of n
items, maximum number of passes is (n - 1). A pass is a situation
where the inner loof has run to its
completion.
The simplest method to sort an unordered list ofvalues using
bubble sort is as follows:
I ' Compare the first and second values, if the first value is greater than
the second value, swap
them.
2' Compare the second and the third values, if the second value is greater
than the third value,
swap them.
3. Keep on comparing adjacent values, swapping them if necessary,
until the last two values in
the array or list have been processed.
This process is repeated n-l times or until all elements are sorted. The
algorithm may be optimised
such that when the elements are sorted before n-l passes, it should
stop.
Note that bubble sort is a sorting algorithm that -ontinuously steps through
a list, swapping items
until they appear in the correct order.
Advantages
. Fairly easy to understand in terms of sorting algorithms
. Fairly easy to write as it comprises very few lines ofcode
. Requires very little memory
Disadvantages
. Relatively slow algorithm which is not suitable for large lists ofitems
233
.Inefncient in terms of time complexity
Standard algorithm for the bubble sort algorithm
Bubble sort algorithm sorts a given unsorted list of items in ascending order.
The identifiers needed for the algorithm are listed below
Identifier Explanation
MyArray [0...7] One-dimension array to store 8 numbers
Maxlndex The last index number of array elements
Pass Control variable for outer loop
, Control variable for inner loop
temp Variable for temporary storage while swapping array elements
Examine the following table. (Note that each pass represents the status ofthe array after the comple-
tion ofthe inner for loop except for pass 0, which represents the array as it was passed to the func-
tion fo! sorting)
8 6 r03 I 2 5 4 )pass0
6 8 3 l2 5 410 )pass I
631254810)pass2
312546810)pass3
| 2 3 4 5 6 8 l0 )pass4
123456810)pass5
123456810)pass6
I23456810)pass7
The above tabulated clearly depicts how bubble sort works. Note that each pass results in one num-
ber being bubbled to the end ofthe list.
234
I
'l-l l; I
Identifier
MyArray [0...3] One-dimension array to store 4 numbers
Maxlndex In" l"rt it d.* nu-b.r of
n .a,rt o* "
Pass
23s
Take note of the effect of the statement n = n - I in the given algorithm. The statement restrict!
algorithm from performing comparison on array elements which are already in the correct posit
The inner loop control variable c, iterates from I to 3 in the first pass, pass l. In pass 2, the inner I
terminates when the control variable is 2. Finally, during pass 3 the inner loop terminates when c
The idea here is to avoid CPU overheads and increase throughput.
Quick Sort
Quick-sort is a sorting algorithm based on the divide-and-conquer paradigm which operates
recursively partitioning the array or list of items to be sorted into two sets. Quicksort is a fast sort
algorithm which swaps items that are a very large distance apart. The quicksort uses complex recun
algorithm which starts by comparing the first and the last elements in the array or lisi. It works
Picking a Pivot item in the list and then moves every item that is greater than the pivot to one s
(right ofpivot) and every item that is less is passed to the other side (left ofpivot). This process cre:
two sub-lists and the two sublists are then recursively passed one after another to the Quick S
algorithm. This procedure of choosing pivot and partitioning the list is applied recursively until sr
lists consisting of only one element. This algorithm is quite efhcient for large-sized data sets. The l<
unravels when the sub-lists are sorted. The quick sort function sorts elements of data structures us
a divide and conquer approach.
Advantages of quicksort
.This is faster sorting method among all for large arrays
.Its efficiency is also relatively good
.It requires relatively small amount of memory
Disadvantages of quiclaort
.It is a complex method of sorting, so it is little hard to implement than other sorting methc
Quick Sort Algorithm
Keypoints
The. quicksort uses a complex recursive algorithm which starts
by comparing the first and last elements
The quicksort algorithm splits up a list into two sul-lists,
11,1.."*"t: poin"ters ur.J move tota
is needed then, a"..
lndcate parrs ot data to be compared and swapped. Ifa swap
reference number is
moved towards_ the other pointer. This pto..r, i, repeated
untir the two pointers .;;"i1". After the
above process the two sub-lists are independent ani
would no longer interact with each other. They
can therefore be sorted separately and the algorithm
can be called ,icursively.
number the
first in the list.
We set two one at each end of the list;
(28) 149 |tn
Compare the two numbers with pointers.
28 > 19, therefore swap and move Ieft to 49.
l9 49 14 lsl l4o ll3 lr8)
. Compare the two numbers with pointers.
28 < 49, therefore swap and move to 13.
le I (28) I4 5l 40 l3 49
Compare the two numbers with pointers.
28 > 13, therefore swap and move the left pointer to 14.
237
<-
. Compare the two numbers with pointers.
. 28 > 14, therefore no and move Left to 51.
_+
. Compare the two numbers with pointers.
. 28 > 51, therefore and move the to 40.
The two pointers are now at the same position and the pivot, 2g,
has been placed at its rightful po-
sition, where elements to the right of it are greater whili those on the left
are smaller. we"no* crc-
ate two sub lists or array that exclude the pivot (28), the left subJist
and the right sublist as shonn
below:
we then perform quicksort technique for the left sub-list until it is sorted. we then perform
on the right sub-list until all elements are sorted. Ifthere are further sublists,
these are sorted
using quicksort method. After all sub-lists are sorted, the elements are joined
into one sorted list
238
Searching Techniques
Searching is finding an item ofdata in a list ofdata items. Searching operation helps find the place of
a given element in the list or whether the element exists in the list. Any search is said to be successful
or unsuccessful depending upon whether the element that is being searched is found or not. There are
several techniques used for searching data in data structures and these include Linear Search, Binary
Search, fump Search, Interpolation Search, Exponential Search and Fibonacci Search. We are going to
discuss and design algorithms for linear and binary search, the rest are beyond the scope of this book.
Linear Search
Linear search, also known as sequential search, is a process that checks every element in the list
sequentially until the desired element is found or until end of list. It is a method for finding a target
value within a list. It sequentially checks each element of the list for the target value until a match is
found or until all the elements have been searched. This method can be performed on a sorted or an
unsorted list (usually arrays). In case ofa sorted list searching starts from Oth element and continues
until the element is found from the list or the element whose value is greater than (assuming the list is
sorted in ascending order), the value being searched is reached. The linear search algorithm searches
for the target value and terminates when the search target is found or upon reaching the end of the
array. Linear search is quite efficient on small searches performed on small arrays. For long lists or
arrays, say, searching a telephone number from a telephone directory linear search is inefrcient. Since
it is critical to determine ifthe search key is present in the array, it may be necessary to search through
the entire array. Given n elements in an array and the search item is the last in the array, the linear
search algorithm would make n comparisons to find the search item.
Key points: Linear search algorithm
. Set up the search criteria
. Examine the first item in the data set
. If there is a match, end the procedure and return the result with match found
. If no match is found, repeat with the next adjacent item
. Ifthe last data item is reached and no match is found, return match not found
A linear search returns the position ofthe search item in the list or display an appropriate message if
the item is not present in the list.
Standard algorithm for linear search
Begin
Get search-key
Repeat for all items in the list
If currentjtem = search-key then
Position = current-item-Position
Print Position
Print Element
Exit loop
End if
If current-item = Iast-item then
Print search-key is not in the list
End if
End Repeat
End
239
Exercise
Dry run the above algorithm using the following items: 4 6 8 l6 t9 and the search-key is 2.
The algorithm can be modified so that it can inform the user that search_key is missing
Let us assume that we have the following sorted array called MyArray
l3 l4 l9 28 40 49 51
Start
Set count = 0
Found = false
Missing = f1l5g
Position = 0
Enter search-key
Repeat
If search-key = MyArray(count) then
Set Found = true
Print Position of search-key
Elseif search-key < MyArray(count) then
Set Missing = true
End if
Increment count by I
Until found = true or count > 6 or missing = true
Stop
Start
Found = False
Position = 0
Enter element to be searched, element
Repeat
If Array (position) = Element THEN
Found = True
Display "Element Found", position
End If
Position = Position + I
Until Found = (True) Or (Position > UB (Aray))
If Found = False THEN
Display "Element does not Exist"
End If
End
240
Actit'ity
1' Modifu the algorithm such that it tests whether the array is not empty before performing tL
array search operation,
2. Design the program code lor the above algorithm in any progrornming language
3, Write an algorithm which determine whether or not the searched data item is present in a
sorted array.
Advantages
. Simple and easy to understand and implement
. Does not require data in the algorithm to be stored in any particular order
Disadvantages
. Not very efficient as it takes a lot ofcomparisons to find a particular record in big files
Binary Search
Binary search is a programming method used to search through data to find out a particular item d
record. The binary search relies on the fact that the data is sorted before it is searched. Binary scard
is a very fast and efficient searching technique. In this method, to search an element you can compan
it with the element at the centre of the list. If there is a match, then the search element is found
otherwise the list is divided into two halves:
. the first half is from the first element to the element immediately before the middle elemenr
(pivot-element_position- I )
. the second half is from the element immediately after the middle element (pivot-element-
position +l) to the last element
241
The searching mechanism proceeds from either ofthe two halves depending upon whether the targ
element is greater or smaller than the central element. If the element is"smaller than the centi
element, then searching is done in the first half, otherwise searching is done in the second half. Binar
search takes far less comparisons than linear search to find a data iiem for 6les that have more than
few items in them. The binary search algorithms are more complicated to write and understand tha
linear search algorithms.
Key point:
Binary.search is a search algorithm which repeatedly divides an ordered/sorted search space in ha
according to how the required value compares with the element at the middle position ofthe list/arra
242
. A faster method when searching a sorted array
Disadvantages
.
It only works with sorted arrays/lists
Start
minimum = 999
REPEAT for all items in the list
IF current-item < minimum THEN
minimum = current item
END IF
END REPEAT
Displayminimum
Stop
243
Standard algorithm to find maximum value
It is common that the maximum value from a list of items is required. For instance, one
may be asked to record examination marks and return the largest mark. In this case the
prerequisite knowledge of find maxirnurn standard algorithm would become handy. The variable
that would store the maximum value from a list should be initialised to a very small value.
Start
maximum = 0
REPEAT for all items in the list
IF current_item > maximum THEN
maximum = current item
END IF
END REPEAT
Displaymaximum
Stop
Get search-item
occurrences = 0
RIPEAT for all items in the list
IF current-item = search-item THEN
occurrences = occurrences + I
END IF
END REPEAT
Display occurrences
Data Structures
A data structure is a collection of different data items that are stored together in a clearly defined way.
A data structure is a representation of the logical relationship existing between individual elements
ofdata. This is a way oforganising all data items that considers not only the elements stored but also
the relationship to each other. The representation ofparticular data structure in the main memory of
a computer is called a storage structure. The storage structure representation in auxiliary memory is
called file structure. In summary data structure is defined as a walof storing and manipulating data
in organised form so that it can be used efficiently.
244
Classification of Data structures
Data structures are usually classified into two main categories namely
. Primitive data structures
. Non-primitive data structures
Data types
In computer systems, data stored in data structures must belong to a particular data
type. Before one
enters data into a comPuter system, there is paramount need to tell the computer
what type of data it is.
The computer stores and processes diferent types ofdata in different ways, hence
the daia type should
be known to the computer beforehand. Data type refers to a particular kind
of data item as defined
by the values it can take, the programming language used or the operations that can be performed on
it. Further, data type is a way of classiffing various types ofdata such as integer, string,
Boolean and
so forth which determines the values that can be used with the corresponding
type of data and the
oPerations that can be performed on the corresponding type of data. For example, given
the string
data type, the allowable values include names ofschools (Hartzell High,School,
Shundure Secondary
School and St Augustinet High school) and operations like arithmetic operations
are not allowable on
such data. Also note that the data type of a variable determines how much space
it occupies in storage
and how the bit pattern stored is interpreted.
.
These are basic structures which are directly operated upon by the machine primitive
instructions.
data structures are synonymous to data types and have diferent representations
on different computer
systems. ExamPles ofprimitive data structures include iltegers, floats, character, pointers and Boolean.
These data tyltes are available as built in type in most programming languages.
The primitive data
t)?es are dealt with in detail in book 5. Howevet some brief explanations are given here on
some of
the data types.
245
An Integer is a data type which allows all values without fraction part, that is, whole numbers
only are allowable. An Example of an integer is 7.
Float is a data type which is used for storing fractional numbers. An example ofa floating
number is 2.15.
Character is a data tlpe which is used to store character values which include a single alpha-
betic letter.
A pointer is a variable that holds the memory address ofanother variable.
Advantages Advantages
. Ability to efficiently add, remove or . Easy to check for overflow
modiS elements . The memory allocation is fixed and so
. Flexible size there will be no problem with adding and
. Effective use of resources because removing data items
resources are allocated during runtime as . Easier to program as there is no need to
required check on data structure size at any point
. Compiler can allocate space during
compilation
. Faster access to elements (when compared
with dynamic data structures) |
Disadvantages
I Disadvantages
. Slower access to elements when compared . Can be very inefficient as the memory
with static data structures | for the data structure has been set aside
. Because the memory allocation is II regardless of whether it is needed or not
dynamic, it is possible for the structure the program is executing
to overflow should it exceed its allowed I Programmer has to estimate the
limit. It can also underflow should it maximum amount of space that is going
become empty to be needed
. Harder to program as the software needs . Can waste a lot ofspace
to keep track of its size and data item . Add, remove.or modifi elements is not
locations at all times directly possible. [f done, it is a resource
. Can be slow to implement searches consuming process
I
Arrays
An array is a data structure which can store multiple homogenous data elements
under one name.
Suppose there are names ofall the students in a class ofsize N which needs
to be stored in a computer
program. This can be done by taking N different variabtes for each student.
Tfing N = 50, it is not easy
to handle 50 different variables for this problem. Given 50 students, one
need to ;clare 50 variables as
shown below and is cumbersome.
r
Dim Names3 as String
Dim Names4 as String
Dim Names5 as String
Dim Names6 as String
Dim NamesT as String
Truly speaking a better and efncient way should be availed and used to store such data. The array
becomes a solution and an alternative where one need not declare 50 variables for 50 students. The
use of arrays is the best approach to algorithm design and coding in general under such conditions.
An array allows a set of items of identical data type to be stored together using the same identiner
name. It is a fixed size sequenced collection of elements of the same data type, stored using the same
identifier name and are directly accessed via an integer index. It is a data structure which can store
multiple homogenous data elements under one name. AII arrays are dlta structures which contain
elements of homogeneous data type that is stored in contiguous memory locations. An array is one
of the most important data structures. One needs to understand arrays completely and be able to
program arrays using a high-level language of your choice. Arrays are declared in a similar way to
standard variables, except that the array size and dimensions are included. For example, in Visual
Basic.Net, the following declares an array that reserves eight locations in memory and labels these as
'Names':
Each data item is called an element of the array. To reference a particular element a programmer must
use the appropriate index. For example, the following statement assigns data to the 5th element:
Names(4) = 'Mwaunza"
Arrays simplify the processing of similar data. An algorithm for getting five names from the user and
storing them in the array Names is shown below:
248
can be visually rePresented as a list. Remember that an array is a linear data structure
which can store
multiple homogenous data elements under one name. An array is a structured collection of elements
all of the same t1pe, that is given a single name. Each array element is accessed by an index
- an integer
enclsoed within brackets - that indicates the elementt position within the collection.
Array position is
always-started at zero and goes up to one less than the array size. For instance, the array shown below
has eight elements, eight is the size of the array. The number 7 is the maximum index for
this array, one
less than the array size. The lowest address corresponds to the first element and the highest address to
the last element.
The following diagram shows the visual representation of the array Names(7):
Index Element
t0l Mungazi
Ill Kapondeni
I2l Manyeruke
t3l Magwati
I4l Mwaunza
tsl Davies
t6I Praise
17l Davison
Two-dimensional arrays
A two-dimensional array is a data structure in which the array is declared using two indices and can
be visually represented as a table. TWo-dimensional arrays have two subscripts or-indices
to identifi an
element ofthe array. The elernents ofa two-dimensional array are inserted using two loops. The outer
loop passes create rows and the inner loop passes are responsible for columns.
The following diagram shows the visual representation ofan ar."y fri"rrarl!,Ztj,
Each individual element can be referenced by its row and column indices. For example:
249
f,
Friends(0,0) is the data item "Mungazi"
Friends(4,2) is the item "F"
Friends(l,l) is the item "Tungamirai"
one- dimensional arrays and 2 dimensional arrays are covered in chapter 7 of this book.
Stack
The stack is a Last In First Out (LIFO) list
Data is added onto the top ofthe stack and is also removed from the stack top
Only the last item (stack top) can be accessed directly
A stack data structure has two oPerations; pushing and popping
* Pushing is an operation which adds a new item to the top of the stack
* Poppini is an operation which removes an item from the top ofthe stack
. t ,t".t i, a dynamic data structure in that it can grow and shrink according to how much
"
data it contains
. The dynamic nature of the stack makes it a very emcient structure because it only uses as much
memory as it needs and not more.
. Stacks are usefi.rl for solving problems involving binary expression trees
250
Grows upwards
Pop
Top of stack
Bottom of stack
Trees
A tree is a data structure consisting ofnodes organised as a hierarchy
Binary Trees (Binary Search Tree)
' A binary tree is a dynamic data structure, consisting ofa root node and zero, one or two sub-
trees which are organised in a hierarchical way.
' ]here are different types of trees and other trees are beyond the scope of this book except
binary trees
A binary tree is one in which each node has at most two descendants
A binary tree node has at most 2 branches.
Each node is a parent of at most two nodes, a node can have just one child but it canl have
more than two children.
The data items are held in nodes.
The nodes are arranged in layers/levels starting from level 0.
Binary trees are useful data structures which allows for efficient sorting, searching and retrieval
of data as well as keeping a sequence in order when additions and deGtions are Lade.
r
:
Root node
Parents/child
nod€
"'^7"o"
. Branch
* The lines connecting the nodes
. Root
* Refers to the node at the top ofthe tree.
* Means the first node of a tree
* There is only one root node per tree and one path from the root node to any next level
node
* However, each branch can have its branch root.
. Parent
* Any node except the root node has one edge upward to a node called a parent
* Each parent node has at most two children
. child
* The node below a given node connected by its edge downward is called its child
* Each child node has only one parent node
Note that some nodes may be both parent and child nodes. For example, Pasiparovo k a child of Mungazi
and a parent to Mwaunza and Shundure
252
Leaf node/terminal node
* Refers to a node which does not have any child node (last node in a path from the root)
* For example, Shundure is a leafnode
Suhtree
* This represents the descendants ofa node
* A subtree is a set ofnodes and edges comprised ofa parent and all the descendants ofthat
parent.
Depth/Level
* The level ofa node n is the number ofedges on the path from the root node to n
* The depth ofa node is the number ofedges from the root to the node.
* Ifa root node is at level 0, then its child node is at level l, its grandchild is at level 2 and so
on.
. Height
* The height of a tree is equd to the maximum level of any node in the tree.
i The height ofa node is the number ofedges from the node to the deepest leaf.
* The height ofa tree is a height ofthe root.
. Sibling
* Nodes in the tree that are children ofthe same parent
* Nodes that share a common parent are called siblings, for example, Magwati and Marange
are siblings
* Siblings may also be referred to as brother nodes
Visiting
* This refers to checking the value ofthe node when control is on the node
Traversing
* This means passing through nodes in a specific order.
253
t7
I Create the node and insert the data item
For example, given the following names;
Mungazi, Kapondeni, Pasiparova, Mwaunza, Shundure, Manyeruke, Magwati, Marangc
they are placed in a binary tree as follows:
. The 6rst element becomes the root node, i.e. Mungazi
For other names, the bigger ones go to the right and the smaller ones go to the left ofa node
arrived at. Every time start from the root node, until you get to an emPty sPace (null node) to
place the new node.
The subsequent item Kapondeni is less than Mungazi, therefore, branch to the left.
To the left of Mungazi there is no node, create a new node and place the item
The next subsequent item Pasiparova is bigger than Mungazi, therefore, branch to the right.
To the right of Mungazi there is no node, create a new node and place the item
After considering every name given above, the tree is shown below
Data elements may be given in numeric form. For example, given the following numbers:
20, 30, 5, 2, 7, 6, 17, 58, 41
they can be placed in a binary tree using the same principles as given above. Elements less than the
rooiforms the left subtree and those bigger forms the right subtree. The resultant binary tree is shown
below.
254
r
Algorithm for constructing a binary tree.
Phce frst item into root node
For subsequent items, start from root noile
Repeat
If (new item > this noile item) Then
Follow right pointer
Else
Follow left pointer
hdif
Until pointer = 0
Create a new node and Place item at this node
Tree Traversal
. This is the process ofvisiting each node in a binary tree exactly once.
' Traversal oftrees is a recursive function-they call themselves.
' Linear data structures like arrays, stacks, queues and linked lists have only one way to read
the data.
. A hierarchical data structure like a tree can be traversed in diferent ways.
. Common traversal methods are: Pre-Order, In-order and post-Order Traversals.
Pre-Order traversal
The order oftraversal is:
. Visit the Node
255
. Traverse the Left sub-tree
. Traverse the Right sub-tree.
?(
a
(
z4
7. End
256
In-Order Traversal
The order oftraversal is:
.Traverse the Left sub-tree
. Visit the Node
. Traverse the Right sub-tree.
To easily perform in-order traversal, draw an outline around the binary tree structure as shown
below, starting from the left side ofthe root node. As you pass underneath a node, (where the brown
dot is marked), output the data in that node.
A
/.
(
?1
I I (
// \
For the diagram above, the in-order traversal output is shown below:
Kapondeni, Magwati, Manyeruke, Marange, Mungazi, Mwaunza, pasiparova, Shundure
In-order traversal output items in ascending order or in alphabetical order if they are alphabetic
items.
257
Recursive Algorithm for in-order traversal
P r o c e du re tr av ers efro m (P )
lf Tree[P]'Left<>O Then
TraverseJrom(Left)
Endlf
Print (data);
lf Tree(p).Right <> o Then
traversefrott(Right)
endif
endProcedure
Post-Order Traversal
The order of traversal is:
. Traverse the Left sub-tree
. Traverse the Right sub-tree'
. Visit the Node
as shown
an outline around the binary tree structure'
To easily perform pre-order traversal' draw (wherc
node' As you pass to the right side ofa node'
below, starting from the left side ofthe root
blue dot is mJrked), output the data in that node'
I
\)
?
?
the followingoutput:
The post order traversal would produce
Mwaunza' Shundure' Pasiparova'
Magwati, Uo..ngt, Manyeruke' Kapondeni'
is as follows:
The algorithm for Post-order traversal
258
l'
P ro c edure t raver sefrom (P )
lf Tree IP ]. Left <> 0 Then
Traversefrom(Left)
Endlf
lfTree(P).Right <> 0 Then
traverseJrom(Right)
endif
Print (data);
endProcedure
Rebuild a binary tree from the pre-order and in-order traversal ouqrut
etirru.y (r."r.ft) iree can be reconitructed with easy when the outPuts from pre-order and in-order
traversais are given. The major assumption here is that you are
quite familiar with pre-orderand in-
order tree traversals. In a Pre-order sequence, leftmost element is the root ofthe
tree' By searching
all the elements on left
the left most pre-order element in the in-order sequence, we can find out that
side of it are in the left subtree and elements on the right are in the right subtree.
Steps
Mark the first element of the pre-order result as it is the root element
. Search and mark the root element in the in-order result
. Root element will divide the in-order result into left subtree and right subtree
. Draw the tree
. right sub-
Recursively construct left subtree and link it to root.left and recursively construct
tree and link it to root.right, i.e. repeat the stePs till you get the binary tree
Example
Pre-order sequence
Mungazi, Isaac, Davey, Matsairire' Tofambirepi, Mwaunza' Xavier
In-order sequence
Davey, Isaac, Matsairire, Mungazi, Mwaunza, Tofambirepi' Xavier
and mark Mungazi in
The first element on the pre-oider sequence, Mungazi is the root node. Search
the in-order sequence as shown below.
Pre-order
@@@@@@@
@@@@@@@
Draw the tree
259
l'
@
Pre-order
@
@@@ @ @
On the left subtree, the first element on the pre-order sequence, Isaac is the root node. Search
and mark Isaac in the in-order sequence as shown above.
* Looking at the in-order sequence in the left subtree of Mungazi, the following is true
* Davey is on the left side of Isaac, therefore, it forms the left subtree for Isaac.
* Matsairire is on the right side oflsaac, therefore, it forms the right subtree oflsaac.
On the right subtree, the first element on the pre-order sequence, Tofambirepi is the root node.
Search and mark Tofambirepi in the in-order sequence as shown above.
Looking at the in-order sequence in the right subtree of Mungazi, the following is true
Mwaunza is on the left side of Tofambirepi, therefore, it forms the left subtree for Tofam-
birepi.
Xavier is on the right side of Tofambirepi, therefore, it forms the right subtree of Tofambi-
rePr.
* Drawing the binary tree continues
. Last element in the post-order sequence will be the root ofthe tree (root element)
. Search and mark the root element in the in-order result
. The root element will divide the in-order sequence into left subtree and right subtree
. Draw the tree
. Recursively construct left subtree and link it to root.left and recursively construct right sub-
tree and link it to root.right, i.e. repeat the steps till you get the binary tree
Example
In-order sequence
Davey, Isaac, Matsairire, Mungazi, Mwaunza, Tofambirepi, Xavier
Post-order sequence
. Davey, Matsairire, Isaac, Mwaunza, Xavier, Tofambirepi, Mungazi
260
i'
The last element on the post order sequence, Mungazi is the root
node. Search and mark Mungazi in
the in-order sequence as shown below.
Pre-order
@@@@@@@
@@@@@@@
Draw the tree
Pre-order
@
Pre-order
@@@ @ @@
on the left subtree, the last element on the post-order sequence, Isaac is the root node. Search
and mark Isaac in the in-order sequence as shown above.
* Looking at the in-order sequence in the left subtree of Mungazi, the following is true
* Davey is on the left side oflsaac, therefore, it forms
*_ Matsairire is on the right side of Isaac, therefore, the left subtree for Isaac.
it forms the right subtree of Isaac.
on the right subtree, the last element on the post-ord., ,.qu.rri", Tofambirepi is the root
node. Search and mark Tofambirepi in the in-order sequ.rr.. st,own above.
* ",
Looking at the in-order sequence in the right subtree of Mungazi, the following is true
* Mwaunza is on the left side ofTofambirepi, therefore, it forms the left subtree for iofambirepi.
* Xavier is on the right side ofTofambirepi, therefore, it forms the right subtree ofTofambirepi.
r
i-.
I
I
,
a
I
I
I
26r
I\r
Implementation of Binary Trees Using Arrays
In some cases, each node (data) maybe assigned pointers (right and left pointer) as illustrated be-
low:
-
Binary trees can be implemented using left and right pointers for each node. Each node will have thc
following:
. Left pointer
. Right pointer
. Data item /-
262
St
J
Dear reader, the original list used to create the binary tree needs to be available because the
tree
number is derived from the original list position of data item.
Mungazi, Kapondeni, Pasiparova, Mwaunza, Shundure, Manyeruke, Magwati, Marange
'
For examPle, Mwaunza is on position 4 on the list, so Tree numbir for Mwaunza is Tree[4]
I7/
The left and right subtrees ofan operator node represent subexpressions that must be evaluated
before applying the operator at the root of the subtree.
Expression trees are mainly used for analyzing, evaluating and modiffing expressions,
especially complex expressions.
Computers usually does the comPutation in either prefix or postfix (usually postfix).
But for humans, it is easier to understand an Infix expression rather than a prefix. Hence
conversion is needed for human understanding.
Operators and operands are used to construct an expression
* An expression is a sequence of oPerators and operands that does one or a combination of
the following:
. specifies the computation of a value
. designates an object or function
. generates side effects.
In case of nested parenthesis, the innermost palentheses have the highest precedence and are evalu-
ated first.
For example, (((a+b).c)/d)
The order of evaluation is given below.
(((a+b)*c)/d)
r23
. Exponential has the next highest precedence after parentheses.
Ifan expression contains several exponential, evaluation proceeds from right to left. Exponential has
right association or right to left associativity.
For example, anb+c/d^e, the order of evaluation is given below
anb+c/d^e
2 431
. Multiplication, Division and Modulus operators have the same precedence and are evaluated
264
l'
next.
Ifan expression contains several multiplication, division and moduius operators, evaluation pro-
ceeds from left to right (left association).
For example, a*b+c*d
The order of evaluation is given below.
a*b+c*d
132
. Addition and subtraction have the same precedence and are evaluated next (or last).
Ifan expression contains several addition and subtraction operators, evaluation proceeds from left to
right (left association). Thus, the associativity is from left to right.
For example, alb-c+dle
The order of evaluation is given below.
al b-c+d/e
I 342
. Equal has the least precedence and it has a right to left associativity in the event of multiple
equal signs in an expression
Example
(A+B)*C-D+E/F
Determine the order of evaluation as shown below
(A+B)*C-D+E/F
t24s3
The following binary expression tree represents (A+B)*C-D+E/F
.\
I
,
I
I
265
I\/
Infix Expressions
Normal mathematical expressions are written as follows:
A+B
to be
This method is called Infix Notation, because the operator is found between the oPerands
acted upon. Infix notation involves the use of brackets and observes oPerator Precedence,
e'g' BOD-
MAS/BOMDAS.
For example, the expression below is an Infix:
(A+B)*C+(D-A)
Ifthere are no brackets, the expression will give a different answer. It is not easy for the comPuter to
evaluate infix expressions'
Prefix Expressions
the
The Polish^Notation is also called the prefix. In Prefix (Polish) notation, the operator Precedes
erands. For example, the infix expression
A + B is given as: +AB
This has an advantage that it removes ambiguity and avoids use ofbrackets
Postfix Expressions
Reverse Pol-ish Notation (Postfix) is a way of writing mathematical expressions
without using
thesis and brackets, and in which the operands precede the operator' Reverse Polish
Notation is
called postfix. For example, the Infix expression A + B is written as follows in Postfix:
AB+
Likewise, the infix expression (A+B)*C+(D-A) is written asr
AB+C*DA-+
There is no need for brackets in this situation.
Reverse Polish Notation has the following benefits:
. can be Processed directly by reading the expression from left to right
l'
. is free of ambiguities
. does not require brackets
. does not require rules of preccdence
. as in BODMAS/BOMDAS
can be processed using a
stack
Example
(e+s)..c-D+E/F
Consider what is already in
parentheses
(+AB)-C.D+E/F
Let Tl = +AB, the expression becomes
Tl*C_D+E/F
*otession again and apply the
same rules ofprecedence
f.ri:;:tnr and associativiry of operators,
D+
Convert expressions in parentheses
to prefix
(*TlC)-o+(/EF)
Let T2 = *TlC
Let T3 = /EF
The expression becomes
T2-D+T3
Inspect the expression again
,. h"rr. -r*-, a.nd apply the same rules ofprecedence and associativity
ofoperators,
tT2-D)+Tr
267
The expression becomes
(Ta+T3)
Convert the expression in parentheses to prefix
+T4T3
Replace the Tl, T2, T3 and T4 with their respective prefix expressions
Let Tl = +AB
Let T2 = *TlC
Let T3 = /EF
LetT4 = -T2D
268
'l
Conversion of Infix Expression into Reverse polish Notation
' To perform this procedure, the knowledge of operator precedence and associativity is highly
required.
. The operator with the lowest / weakest precedence becomes the root node.
. When the weakest operator is identified, it is placed as the root node.
' ExPressions on the left hand side ofthis weakest operator makes up the left sub tree, while
those on the right hand side makes the right sub-tree.
. This procedure is applied as we move down the tree.
Example
X=A*B+C/D
. The weakest operator is the = sign. So it becomes the root node.
. To its left, there is only X, which becomes a node to the left of
=
'. There are no more items to the left branch of the root node. We therefore go to the right side.
The weakest oPerator to the right of= is +, therefore it becomes the first node to thJ right of
the root.
. To the left ofthe + sign, the weakest sign is the *, which we place as the node to the left of+
. To the left of * there is A, which becomes a node.
. To the right of* there is B, which becomes a node.
. We are now done with the left branch of the + node, let's move to the right side.
. The weakest sign is /, it becomes a node there.
. To its left there is C, which becomes a node.
. To the right ofl there is D, which also becomes a node.
. Thus, all the items are now in a binary tree, which appears as follows:
':r\
269
gr
I
I \
I
I t
) (
I
lt )
Points to note
. If the original expression to be converted contains, brackets or parenthesis, ignore them, that
is, dont put them in the tree, but use them in getting the weakest operator.
Items in brackets have a higher priority and therefore are inserted in the tree later than thosc
NOT in brackets.
Sometimes getting the weakest operators in the correct ,sequence is rather tricky. You are
required to revisit the arithmetic operator precedence and associativity discussed earlier ia
this chapter.
270
1/
I
Algorithm for Infix to Postfix
271
1/
I
f)-i + +*(+ abcdne- Step l: '-' and '+' have same precedence, so th.
associativity of operators is used which is left to
right for + and - operators
Step 2: Pop topmost element, i.e. '-' and print il
on the output string
Step 3: Push '+' operator onto stack because the
current topmost symbol of stack is now '('
)-i f +*(+ abcd^e-f Print operand
-t ) +* abcdne-f+ Step l: Now ')' is topmost Element of Stack, pop
and discard it
Step 2: pop and print all operators one by onc
until the opening bracket. Here there is '+'
operator only
Step 3: pop the opening parenthesis and discard
it as well
abc- Step l: Now'*' priority than incoming
has higher
dae-f+*+ Operator'-', pop topmost element, i.e. '*'. Removr
topmost operator from stack and print it
Step 2: Now '+' has same priority as the incoming
operator '-', pop topmost element, i.e. '+1
Step 3: Remove topmost operator from stack atrd
plint it
Step 4: Now stack becomes empry so push
operator '-' onto stack
null I abc- Print Operand
dre-f+*+i
NULL NULL null abc- Expression Scanning Ends but we have still one
dne-f+*+i- more element in stack so pop and print it
f-
l-
272
\/
I
+
a r) \
*
ab c
(
)
d e
Evaluating Reverse polish erqrressions
A Reverse Polish expression is eialuated'sing
a stack. The procedure is outlined
below:
' Loaded into a stack every operand
enciuntered iitl.
e*p.".siorr, (that is a number or variable)
' Ifthe next symbol is an operator (+, -,-,.. .),
the i;;; two operands in the stack
are popped,
' th.;;il;i"]i. "'
The first popped item is ptaced t"
---- h.t popp"d one is praced to the left,
the operator is placed between tfr. op.rirrar. and
' required by the operator irl*ri.a out
and the result is pushed back into the
*:o:o*""n
Let us assume that the following
postfix expression:
ab+cde-*_
with the following values. a 5,
b=3, c=2, d = 6 and e=4.
. The operands in this =e:rpression are: a, b, c, d and e
. Operators are +, _ and *
+ First a (5) is pushed into the stack
* b (3) is pushed into the stack
* an operator is encountered,
- a (5) is popped and placed ontherefor-e, b (3) is popped and placed on the right
the left
"* the operator (+) is piaced in between and effected
the result (g)is
* c (2) is pushed pushed back into the stack
into the stack
* d (6) is pushed into the stack
* e (4)
* - signisispushed into the stack
encountered. Thus e (4) is popped and placed on the right
is popped and placed tf,. f.n, to gi*
.] i(01
Operator (-) is effected "" ial.l
* The result (2) is pushed back into
* Another operator is encountered(*)
the stack.
t Result (2) is popped
273
1/
a
* C (2) is popped and operator effected
. rtr. ,.r,rlt ii) it pu'nta back to the stack'
' OPerator (-) again is encountered
- Result(4) is PoPPed
* Anoth"r.erutila; ls popped and operator effected
* Result (4) is pushed into the stack
* There are no more oPerators' The answer
is displayed'
nn.
A_r),"n
HI-H H
Conversion from postfix expression to infix
expression
This can be done using a stack data structure
Algorithm
FOR each symbol in postfix-expression
Reai one symbol from the postfx expression
If the sYmbol is an oPerand then
Push the symbol onto the stack toP
Elseif the symbol is an operator then
Pop the last two ;;;;:;;' tt"* l"p' place the first popped element on the righr
*d th. lott popped element on the left parentheses maybe introduced
Place the operator in between the two operands'
Push the resulting infix expression onto
the stack top
End if
NEXT symbol\
Example
Conve-rt AB+C*D-EF/+ into infix expression
E
stack top expression
Reading of Postfx
A A
I
) B B
til
274
I
3 + (A+B)
A
4 C C
C
(A+B)
5
(A+B)*C
(A+B)*C
6 D D
7 (A+B)*C-D
8 E E
9 F F
l0 EIF
(A+B)*C-D
ll + (A+B)*C-D+E/F
(A+B).C-D+E/F
Algorithm
Reverse the infx expression
FOR each symbol in postfix_expression
Read one symbol from the postfix expression
Ifthe symbol is an operand then
the symbol onto the stack top
- _Push
Elseifthe symbol is an operator then
Pop the last two operands on the stack top, place the
first popped element on the left
and- the rast popped element on the right (bicause
of the riviri" o'"rion p"rpr^ra
earlier)
Place the operator in between the two operands, parentheses
may be introduced
Push the resulting infix expression ontoihe stack
top
End if
NEXT symbol
Given a prefix expression like +-*+ABCD/EF
Reverse it to have FE/DCBA+*-+
275
,'
Reading ofpostfix stack top expressron
I F F
t E E
3 E/F
4 D D
5 C C
6 B B
.7
A A A
B
c
D
E/F
8 + (A+B) (A+B)
C
D
EIF
9 (A+B)*C (A+B)*C
l0 (A+B)*C-D
G_r
ll + (A+B)*C-D+E/F
I ra*sl-c-p*srr I
276
End of chapter questions
,
data structure, giving an advantage
(c) The details ofa car part
ofeach. V)
,tor-"d in a binary tree according to this
Begin ".. algorithm
Read Value New_part
Start At Root Node
While Node Not Empry Do
If New_part < Value At Node Then
Follow Left Subtree
Else
Follow Right Subtree
Endif
Endwhile
Insert New_part At Node
End
(t) Show the binary tree after the following
values have been input
Radio V, isor. Brakes Tyres Alternator
(ii) Explain how Clutch is added to
Windscreen t3]
(iii), Describe an argorithm that
(i).
the tree in
t5l
.
read in alphabetic order.
can be appliJ ,o,h. brn"ry tree of car parts,
so that the tree is
t3l
4 The fo owing binary tree diagram contains
a number ofintegers. In each case the
pointer indicates the condition "highir number" right
and the left pointer indicates the condition .,lower
or equal number'l
277
1/
t I
t. Write down the integer contained in the root node'
ii. ;:il ]i# il. il"?ililfi; iles would be accessed to 6nd the integer 252& [u
rr,r lr'
tfre,iieser 3-lL6-:::t-1T""ji:1
.
iii. Copy the tree ana ,f,o* *t "r. " n"* "oat 1*"t1i"g li
iv. ;ril#;*,;;;,;'t;;;;ru-. e*pr"in,"r,at-would happen if a search was made fa
this code.
Hint:createabinarytreestructure,thenPerformimplementationoftreesusingarrays
278
I I
\/
I I
Convert the following infix string to postfix string
f, _
Y+WIX*Y|Z
10' write an algorithm that sums a series that starts with t3l0.01 and ends with 1.0. The numbers in
the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so
on,
l.
I write an algorithm that uses nested for loops to print a multiprication table.
L2' Write an algorithm that prompts the user to entei two positive integers
and 6nds their greatest
common divisor lit
l3' You have just started a sales job in a department store. Your pay
consists ofa base salary and a
commission. The base salary is $5,000. The scheme shown below is used
to determine the commission
rate.
Sales Amount Commission Rate
$0.01-$s,000 8 percent
$s,000.01-$ 10,000 l0 percent
$10,000.01 and above 12 percent
Your goal is to earn $30,000 in a year. write an algorithm that will find
out the minimum amount of
sales you have to generate in order to make $30,000. tl2l
14. write an algorithm that prompts the user to enter an integer from l to 15 and disprays
a pyr-
amid. For example, if the input integer is 5, the output is shown b-elow.
Il0l
I
2r2
32123
432t234
543212345
15. write a pseudocode that displays the first 50 prime numbers in five lines, each of which
contains l0 numbers. An integer greater than I is prime ifits only positive
divisor is 1 or itself.
For
example,2,3,5, and 7 are prime numbers, but 4, 6, S, and I are noi.
[10]
16' A school teacher is working on her students'end of term marks. write an algorithm which
helps the teacher to find the largest mark, average mark and lowest "of
mark for .l"r* 40 students.
ll0l "
17. write an algorithm to search and display the name Davey from the following list of names:
Agrippa' Andrew Ashley, Davies, Davison, Deborah, praise, wayne, Tinaye, sandri
Marian, Mi-
cheilla, Davey, |anet [l0i
18. Use to case/s\'\'itch structure to write an algorithm which calculates the
area ofthe following
sha-pes; circle, trapezium, rectangle and triangle. [t0]
Reference
https://youtu.be/7cnR:fPwygk infix to prefix conversion examples data structures
I I by bhanu priya
hltp://www.teachifrme.com/a-level-computer-science-past-papers/
Kalicharan N
t-
Langfield S and Dudell
Heathcote P M. and Landfield S
/-
I
279
ir''
I