Cit 237
Cit 237
COURSE
GUIDE
CIT 237
PROGRAMMING AND ALGORITHMS
ii
CIT 237 COURSE GUIDE
Abuja Office
No. 5 Dares Salaam Street
Off Aminu Kano Crescent
Wuse II, Abuja
Nigeria.
e-mail: centralinfo@nou.edu.ng
URL: www.nou.edu.ng
Published by
National Open University of Nigeria
iii
CIT 237 COURSE GUIDE
CONTENTS PAGE
Introduction................................................................................ 1
What You will Learn in this
Course............................................ 1
Course Aims............................................................................... 2
Course Objectives...................................................................... 2
Working through this Course.................................................... 3
Course Materials........................................................................ 3
Study Units ............................................................................... 3
Textbooks and References ........................................................ 4
Assignment File........................................................................ 7
Presentation Schedule............................................................... 8
Assessment...................................................................
............. 8
Tutor-Marked Assignment ....................................................... 8
Final Examinations and Grading............................................... 9
Course Marking Scheme............................................................ 9
Course Overview………………………………………………
10
How to Get the Best from this
Course ...................................... 11
Facilitators/Tutors and Tutorials .............................................. 12
Summary .................................................................................. 13
iii
Introduction
This course is divided into three modules. The first module deals with
the basic introduction to the concept of programming and algorithms;
such as definition and characteristics of algorithms, basic data types and
fundamental data stuructures, program development life cycle, types of
programming languages, language translators and their characteristics,
tools for program design, etc.
The third module deals with sorting and some special problems. It
introduces you to some sorting and divide-and-conquer algorithms after
which it goes on to discuss some sorting techniques such as Merge Sort,
Bubble Sort, Selection Sort, etc. giving their algorithms and
performance analysis.
The aim of this course is to equip you with the basic knowledge of
writing efficient programs through the use of concise and efficient
algorithms. By the end of the course, you should be able to confidently
tackle any programming problem breaking it into its component parts,
write efficient algorithms to solve the problem and implement the
algorithm using any programming language of your choice as well as
being able to evaluate and measure the performance efficiency of any
algorithm.
This Course Guide gives you a brief overview of the course content,
course duration, and course materials.
Course Aims
Course Objectives
Certain objectives have been set out to ensure that the course achieves
its aims. Apart from the course objectives, every unit of this course has
set objectives. In the course of the study, you will need to find out, at the
end of each unit, if you have met the objectives set at the beginning of
the unit. By the end of this course you should be able to:
ii
CIT 237 PROGRAMMING AND ALGORITHMS
Course Materials
These include:
Study Units
iii
CIT 237 PROGRAMMING AND ALGORITHMS
www.doc.ic.ac.uk/~wjk/C++Intro/
www.personal.kent.edu/~muhama/Algorithms
www.eslearning.algorithm.com
www.eslearning.algorithm.com
iv
CIT 237 PROGRAMMING AND ALGORITHMS
http://mathworld.wolfram.com/QueensProblem.html.
Conrad, A.; Hindrichs, T.; Morsy, H.; and Wegener, I.( 1994). "Solution
of the Knight's Hamiltonian Path Problem on Chessboards."
Discr. Appl. Math. 50, 125-134.
http://www.chessbase.com/columns/column.asp?pid=163.
v
CIT 237 PROGRAMMING AND ALGORITHMS
vi
CIT 237 PROGRAMMING AND ALGORITHMS
vii
CIT 237 PROGRAMMING AND ALGORITHMS
Assignments File
These are of two types: One for the Self-Assessment Exercises and the
other for the Tutor-Marked Assignments. The self-assessment exercises
will enable you monitor your performance by yourself, while the tutor-
marked assignments will be supervised . The assignments take a certain
percentage of your total score in this course. The tutor-marked
assignments will be assessed by your tutor within a specified period.
The examination at the end of this course will aim at determining your
level of mastery of the subject matter. This course includes 21 tutor-
marked assignments and each must be done and submitted as stipulated
Your best scores however, will be recorded for you. Be sure to send
these assignments to your tutor before the deadline to avoid loss of
marks.
Presentation Schedule
Assessment
There are two aspects to the assessment of the course. First are the tutor
marked assignments; second, is a written examination.
At the end of the course, you will need to sit for a final three-hour
examination. This will also count for 70% of your total course mark.
Tutor-Marked Assignment
Assignment questions for the units in this course are contained in the
Assignment File. You should be able to complete your assignments
viii
CIT 237 PROGRAMMING AND ALGORITHMS
When you have completed each assignment, send it together with a form
to your tutor. Make sure that each assignment reaches your tutor on or
before the deadline given. If however, you cannot complete your work
on time, contact your tutor before the assignment is done to discuss the
possibility of an extension.
The final examination for the course will carry 70% percentage of the
total marks available for this course. The examination will cover every
aspect of the course, so you are advised to revise all your corrected
assignments before the examination.
This course endows you with the status of a teacher and that of a learner.
This means that you teach yourself and that you learn, as your learning
capabilities would allow. It also means that you are in a better position
to determine and to ascertain the what, the how, and the when of your
learning. No teacher imposes any method of leaming on you.
The course units are similarly designed with the introduction following
the table of contents, then a set of objectives and then the dicourse and
so on.
The objectives guide you as you go through the units to ascertain your
knowledge of the required terms and expressions.
This table shows how the actual course marking is broken down.
Assessment Marks
Assignment 1- 4 Four assignments, best three marks of the
four count at 30% of course marks
Final Examination 70% of overall course marks
Total 100% of course marks
ix
CIT 237 PROGRAMMING AND ALGORITHMS
Course Overview
x
CIT 237 PROGRAMMING AND ALGORITHMS
In distance learning the study units replace the university lecturer. This
is one of the great advantages of distance learning; you can read and
work through specially designed study materials at your own pace, and
at a time and place that suit you best. Think of it as reading the lecture
instead of listening to a lecturer. In the same way that a lecturer might
set you some reading to do, the study units tell you when to read your
set books or other material. Just as a lecturer might give you an in-class
exercise, your study units provide exercises for you to do at appropriate
points.
Each of the study units follows a common format. The first item is an
introduction to the subject matter of the unit and how a particular unit is
integrated with the other units and the course as a whole. Next is a set
of learning objectives. These objectives enable you know what you
should be able to do by the time you have completed the unit. You
should use these objectives to guide your study. When you have
finished the units you must go back and check whether you have
achieved the objectives. If you make a habit of doing this you will
significantly improve your chances of passing the course.
Remember that your tutor’s job is to assist you. When you need help,
don’t hesitate to call and ask him or her to provide it.
3. Once you have created your own study schedule, do everything you
can to stick to it. The major reason students fail is that they lag
behind in their course work.
4. Turn to Unit 1 and read the introduction and the objectives for the
unit.
5. Assemble the study materials. Information about what you need for
a unit is given in the Overview at the beginning of each unit. You
will almost always need both the study unit you are working on and
one of your set of books on your desk at the same time.
xi
CIT 237 PROGRAMMING AND ALGORITHMS
6. Work through the unit. The content of the unit itself has been
arranged to provide a sequence for you to follow. As you work
through the unit you will be instructed to read sections from your set
books or other articles. Use the unit to guide your reading.
7. Review the objectives for each study unit to confirm that you have
achieved them. If you feel unsure about any of the objectives, review
the study material or consult your tutor.
8. When you are confident that you have achieved a unit’s objectives,
you can then start on the next unit. Proceed unit by unit through the
course and try to pace your study so that you keep yourself on
schedule.
10. After completing the last unit, review the course and prepare yourself
for the final examination. Check that you have achieved the unit
objectives (listed at the beginning of each unit) and the course
objectives (listed in this Course Guide).
Your tutor will mark and comment on your assignments, keep a close
watch on your progress and on any difficulties you might encounter and
provide assistance for you during the course. You must mail or submit
your tutor-marked assignments to your tutor well before the due date (at
least two working days are required). They will be marked by your tutor
and returned to you as soon as possible.
• you do not understand any part of the study units or the assigned
readings,
xii
CIT 237 PROGRAMMING AND ALGORITHMS
You should try your best to attend the tutorials. This is the only chance
to have a face to face contact with your tutor and to ask questions which
are answered instantly. You can raise any problem encountered in the
course of your study. To gain the maximum benefit from course
tutorials, prepare a question list before attending the classes. You will
learn a lot from participating in discussions actively.
Summary
I wish you success with the course and hope that you will find it
interesting and useful.
xiii
CIT 237 PROGRAMMING AND ALGORITHMS
MAIN
COURSE
Course Code CIT 237
xiv
CIT 237 PROGRAMMING AND ALGORITHMS
Abuja Office
No. 5 Dares Salaam Street
Off Aminu Kano Crescent
Wuse II, Abuja
Nigeria.
e-mail: centralinfo@nou.edu.ng
URL: www.nou.edu.ng
Published by
National Open University of Nigeria
ISBN: 978-058-581-8
xv
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS PAGE
xvi
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Meaning and Significance of Programming
3.2 Levels of Programming Languages
3.3 Features of Programming Languages
3.4 Programming Methodologies and Application Areas
3.5 Language Translators
3.6 The Programming Environment
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
1
CIT 237 PROGRAMMING AND ALGORITHMS
2
CIT 237 PROGRAMMING AND ALGORITHMS
3
CIT 237 PROGRAMMING AND ALGORITHMS
3.4.1 Methodologies
4
CIT 237 PROGRAMMING AND ALGORITHMS
5
CIT 237 PROGRAMMING AND ALGORITHMS
3.5 Translators
6
CIT 237 PROGRAMMING AND ALGORITHMS
into object code before the entire program is executed while the
interpreter translates the source instructions line by line. In the
former, the computer immediately executes one instruction
before translating the next instruction.
7
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
5.0 SUMMARY
8
CIT 237 PROGRAMMING AND ALGORITHMS
Write out any ten programming languages stating the application areas
in which they could be made use of and the type of translators they use
www.doc.ic.ac.uk/~wjk/C++Intro/
9
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Program Development Cycle C 7, D4
3.2 Program Execution Stages
3.3 Principles of Good Programming Style
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
10
CIT 237 PROGRAMMING AND ALGORITHMS
11
CIT 237 PROGRAMMING AND ALGORITHMS
The normal program execution consists of four (4) stages (See figure
2.1), though some programming languages like BASIC combine two or
three of these in one single process. The program execution stages are
explained below:-
Data Data
Program
(Source Object
Compilation Output
Code) Code
12
CIT 237 PROGRAMMING AND ALGORITHMS
reported.
- The Output: The last stage is for the computer to give the
13
CIT 237 PROGRAMMING AND ALGORITHMS
14
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
In the course of the program the student should be able to write a good
program following a good programming convention, apart from learning
the cycle of program development. The programme execution stages are
also not left out of this unit.
5.0 SUMMARY
15
CIT 237 PROGRAMMING AND ALGORITHMS
www.doc.ic.ac.uk/~wjk/C++Intro/
16
CIT 237 PROGRAMMING AND ALGORITHMS
www.personal.kent.edu/~muhama/Algorithms
17
CIT 237 PROGRAMMING AND ALGORITHMS
UNIT 3 ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Introduction to AlgorithmsA page 3
3.2 Computational Problems and Algorithms
3.3 Characteristics of Algorithm C
3.4 Algorithm Design and Analysis Stages A page 9
3.5 Types of Major Computing Problems A page 19
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
18
CIT 237 PROGRAMMING AND ALGORITHMS
Problem definition
Problem analysis
Algorithm
As shown in the above figure, after a problem has been identified, the
problem is then carefully analysed in order to present a suitable
algorithm. An algorithm is then designed and presented to the computer
in a particular programming language. The computer will then generate
the output, based on the input.
Definition 4: A correct algorithm halts with the correct output for every
input instance. We can then simply say that an algorithm is a procedure
for solving computational problems
19
CIT 237 PROGRAMMING AND ALGORITHMS
Problem definition
Algorithmic Decisions
Algorithm Design
Evaluation
Analysis
Coding
Problem Definition
20
CIT 237 PROGRAMMING AND ALGORITHMS
After the programmer has fully understood the problem, all he/she needs
do, is to identify the computational requirement(s) needed to solve the
problem.
Algorithm Design
In this phase the programmer battles with the problem of how he or she
should design an algorithm to solve the given problem. Also, the
programmer specifies the fashion which the algorithm will follow, either
pseudo code algorithm fashion or Euclid algorithm fashion.
Algorithm Evaluation
Since an algorithm has been specified, you have to prove its correctness.
That is, you have to prove that the algorithm yields a required result for
every legitimate input in a finite amount of time.
Algorithm Analysis
21
CIT 237 PROGRAMMING AND ALGORITHMS
1. Non-recursive Algorithms
These are algorithms that do not recall back the same algorithm or
function. For example, write a program to generate Fibonacci sequence.
M=1
N=2
I=2
WRITE M
WRITE N
30 L=N
N=N+M
WRITE N
M=L
I = I+1
IF I <= 30 GOTO 30
END
2. Recursive Algorithms
These are algorithms that have the same function calling themselves.
For example, the recursive algorithm for the Fibonacci example is.
Algorithm f (n)
F (0)=0;
F (1)= 1;
For I= 2 to N
F (I) = F (I-1) + F ( I-2);
RETURN F (N);
In this algorithm, we can see functions like F (I-1), F (I), F (I-2) calling /
referring to the same algorithm. This case is also referred to as a
recursion.
4.0 CONCLUSION
In this unit, you have learnt how to design an efficient algorithm. You
were also shown the difference between computational problems and
algorithms. This unit also explained the stages in the design of an
efficient algorithm.
22
CIT 237 PROGRAMMING AND ALGORITHMS
5.0 SUMMARY
www.doc.ic.ac.uk/~wjk/C++Intro/
23
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Introduction
3.2 Flowcharts
3.3 Pseudocodes
4.0 Conclusion
5.0 Summary
6.0 Tutor-marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
3.0MAIN CONTENT
24
CIT 237 PROGRAMMING AND ALGORITHMS
Solution:
1. Start
2. Get the first number
3. Get the second number
4. Add the two numbers together
5. Show the result
6. Stop
3.2Flowcharts
25
CIT 237 PROGRAMMING AND ALGORITHMS
26
CIT 237 PROGRAMMING AND ALGORITHMS
Start Terminal
Read the
Input
first No (A)
Read the
second Input
number (A)
Show the
result Output
(display C)
Stop Terminal
Figure 5: The flowchart for the postage stamp problem
3.3Pseudo Codes
27
CIT 237 PROGRAMMING AND ALGORITHMS
Step 1 Start
Step 2 Input A
Step 3 Input B
Step 4 C=A+B
Step 5 Print C
Step 6 Stop
4.0 CONCLUSION
5.0 SUMMARY
This unity has dealt with programming tools (flow-charts and pseudo
code). It has also showed the diagrams used and the English-like
statements used to represent an algorithm. The unit also stated the
advantages of both pseudo codes and flow charts.
Using the flowchart only, design an algorithm to find the mean of five
numbers.
www.doc.ic.ac.uk/~wjk/C++Intro/
www.personal.kent.edu/~muhama/Algorithms
28
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Program Testing
3.2 Program Documentation
3.3 Program Maintenance
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
Program testing is done in a way that the program is run on some test
cases and the results of the program’s performance are examined to
check whether the program is working as expected. It is also important
to perform a test process on every condition or attribute that determines
the effective/correct functionality of the system. The testing process
normally begins with selecting the test factor(s). The test factors
determine whether the program is working correctly and efficiently.
29
CIT 237 PROGRAMMING AND ALGORITHMS
• Stress testing
• Recovery testing
• Compliance testing
• Execution testing
• Operations testing
• Security testing
30
CIT 237 PROGRAMMING AND ALGORITHMS
• Requirement testing
• Error-handling testing
• Inter-systems testing
• Parallel testing
• Regressing testing
• Manual-support testing
• Control test
31
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
This unit has explained some of the reasons why you should maintain
your program. It has further explained two major reasons for program
documentation. It introduced program testing as well as the reasons for
carrying out in our program.
32
CIT 237 PROGRAMMING AND ALGORITHMS
5.0 SUMMARY
What this unit explains is the reason why you should maintain your
programs and why program testing is a labour intensive task. It also
explained and gave instances of types of programming testing and the
techniques used in carrying them out.
www.doc.ic.ac.uk/~wjk/C++Intro/
www.personal.kent.edu/~muhama/Algorithms
33
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Data and Programming
3.2 Numeric Data Types
3.3 Non-numeric Data Types
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will be introduced to the various forms in which data
can be represented Data Structures). You will also be introduced to the
different data types, like integers, real numbers, character data type and
string data type.
2.0 OBJECTIVES
By the time you must have completed this unit, you should be able to:
Data serve as input to most programs. The format or procedure for input
specification within a program depends on the nature of data.
34
CIT 237 PROGRAMMING AND ALGORITHMS
• Bytes
• Shortint
• Integer
• Word
• Long int
Mantissa = 0.4923425
Exponent = 5
So we have 0.4923425E5.
• Real
• Single
• Double
• Extended
35
CIT 237 PROGRAMMING AND ALGORITHMS
These are valves that are not numbers in nature. Examples are
For example
- “Abiola”
- “I am a man”
- “1999”
4.0 CONCLUSION
5.0 SUMMARY
• There are basically two types of data types, which are numeric and
non numeric data types.
• Numeric data types are either integers or real numbers.
• Non numeric data types are either character or string.
Write and explain any example of a numeric and non-numeric data type.
36
CIT 237 PROGRAMMING AND ALGORITHMS
www.doc.ic.ac.uk/~wjk/C++Intro/
www.doc.ic.ac.uk/~wjk/C++Intro/
www.personal.kent.edu/~muhama/Algorithms
37
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Introduction to Data Structure
3.2 Linear Data Structures A 26
3.3 Graphs A 28
3.4 Trees A 32
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit is intended to show you the various ways of representing data
in an algorithm and in programming as a whole.
2.0 OBJECTIVES
38
CIT 237 PROGRAMMING AND ALGORITHMS
Queue: Unlike the stack, a queue is a data structure with two ends, in
which an insertion is made at a end (REAR) and a deletion is done at the
other end (FRONT). A queue operates a First-In-First-Out (FIFO)
scheme. A typical and practical illustration of this data structure is a
queue in a modern entry. Queues are used for several graph problems.
39
CIT 237 PROGRAMMING AND ALGORITHMS
The figure below represents the graph G with four vertices A,B,C & D
and five edges e1=(A,B), e2=(B,C), e3= (C,D), e4=(A,C), e5=(B,D).
A B
D C
3.4 TREES
There are some properties possessed by trees which graphs do not have;
for instance, the number of edges in a tree is always one less the number
of its vertices.
\E\ = |V| - 1.
40
CIT 237 PROGRAMMING AND ALGORITHMS
a b a b h
c d c d e i
f g f g j
i d a
b d e
c b a e
c g f
h g f h i
4.0 CONCLUSION
In the course of this unit you were introduced to the concept of data
structure and the various data structures that are available.
5.0 SUMMARY
41
CIT 237 PROGRAMMING AND ALGORITHMS
www.doc.ic.ac.uk/~wjk/C++Intro/
www.personal.kent.edu/~muhama/Algorithms
42
CIT 237 PROGRAMMING AND ALGORITHMS
UNIT 8 EXERCISE I
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Exercise
3.2 Solution
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit is a recap of the module because it will expose you to the
practical aspect of what the module has taught.
2.0 OBJECTIVES
3.2 Solution
a. Pseudocodes
I=1
WRITE 1
FOR I = 2, I – 1
FOR J = 2, I – 1
IF MOD (I, J) = 0
GOTO 20
ENDIF
NEXT J
WRITE “I”
20 NEXT I
43
CIT 237 PROGRAMMING AND ALGORITHMS
Note
b. Flowchart
44
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
The unit is a practical approach to the module and it is necessary for you
to have a solid experience in the development of an algorithm and a
flow chart as a pre-requisite for the remaining part of the course.
5.0 SUMMARY
You should be able to develop an algorithm and a flow chart for the
algorithm
www.personal.kent.edu/~muhama/Algorithms
45
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Efficiency Attributes
3.2 Measuring Input Size
3.3 Units for Measuring Running Time
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0INTRODUCTION
This unit will introduce you to the criteria used in analysing the
performance of an algorithm. As you will see, this unit is an introduction
to other units in this module.
2.0OBJECTIVES
46
CIT 237 PROGRAMMING AND ALGORITHMS
It is certain that all algorithms do not run at a time on the same number
of input(s). For example, it takes longer to sort larger arrays, multiply
larger matrices, and so on. It is then necessary to investigate an
algorithm’s efficiency, as a function of input size parameter n. Selecting
such a parameter is not difficult in most problems. For example, it will
be the size of the list for problems of sorting, searching, finding the list’s
smallest element, and most other problems dealing with lists. For the
problem of evaluating a polynomial P(x) = anxn +….+ a0 of degree n, it
will be the polynomial’s degree or the number of its coefficients, which
is larger by one than its degree.
47
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
5.0 SUMMARY
Having gone through this unit, you are expected to have learnt the
following:
48
CIT 237 PROGRAMMING AND ALGORITHMS
www.eslearning.algorithm.com
www.personal,kent.edu/wmuhama/algorithms.
49
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Informal Notation
3.2 o - Notation
3.3 O - Notation
3.4 θ - Notation
3.5 ∼ - Notation
3.6 Ω- Notation
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit introduces and explains order of growth and the different
notations that are used to represent order of growth of algorithms.
2.0 OBJECTIVES
3.1Informal Introduction
50
CIT 237 PROGRAMMING AND ALGORITHMS
All the functions are based on input size n. We can see that the function
growing the slowest among these is the logarithmic function. It grows so
slowly, in fact, that we should expect a program implementing an
algorithm with a logarithmic basic-operation count to run practically
instantaneously on inputs of all realistic sizes.
On the other end of the spectrum are the exponential function 2n and the
factorial function n. Both these functions grow so fast that their values
become astronomically large, even for rather small values of n.
3.1o-Notation
This is pronounced as “little oh of”. Let ƒ(x) and g (x) be two functions
of x. Each of the five symbols above is intended to compare the rapidity
of growth of ƒ and g. If we say that ƒ(x) = o (g (x)), then informally we
are saying that ƒ grows more slowly than g does when x is very large.
Definition
We say that ƒ(x) = o (g (x)) (ƒ(x→ ∞) If limx → ∞, ƒ(x)/g (x) exists and
is equal to 0.
Here are some examples:
1.X2 = o(x5)
2. Sin x = o (x)
3.14.709 √x = o (x/2 + 7 cos x)
3.2O-Notation
51
CIT 237 PROGRAMMING AND ALGORITHMS
grow at the same rate or it might grow more slowly; both are
possibilities that the ‘O’ permits.
Definition
We say that ƒ(x) = O (g (x)) (x → ∞) if ∃C, xo such that |ƒ(x) | < Cg (x)
(∀x > xo).
The qualifier ‘x→ ∞’ will usually be omitted, since it will be understood
that we will most often be interested in large values of the variables that
are involved.
For example, it is certainly true that sin x = O (x), but even more can be
said, namely that sin x = O (1). Also x3 + 5x2 + 77 cos x = O (x5) and 1/
(1 + x2) = O (1). Now we can see how the ‘o’ gives more precise
information that the ‘O’, for we can sharpen the last example by saying
that 1/(1 + x2) = o (1). This is sharper because not only does it tell us
that the function is bounded when x is large, we learn that the function
actually approaches 0 as x → ∞.
3.3 θ-Notation
Definition
We say that ƒ(x) = θ(g(x)) if there are constants c1 > 0, c2 > 0, xo such
that for all x > xo it is true that c1g(x) < ƒ(x) < c2g(x).
We might then say that ƒ and g are of the same rate of growth, only the
multiplicative constants are uncertain. Some examples of the ‘θ’ at work
are
(X + 1) 2 = θ(3X2)
(x2 + 5x + 7)/(5x3 + 7x + 2) = θ(1/x)
3 + √2x = θ(x ¼)
(1 + 3/x)x = θ(1).
The ‘θ’ is much more precise than either the ‘O’ or the ‘o’. If we know
that ƒ(x) = θ(x2), then we know that ƒ(x)/x2 stays between two nonzero
constants for all sufficiently large values of x. The rate of growth of ƒ is
established: it grows quadratic ally with x.
52
CIT 237 PROGRAMMING AND ALGORITHMS
3.4 ∼- Notation
Definition
2x + 7 log x + cos x ∼ 2x
3.5 Ω- Notation
This is pronounced, as “is omega of”. The last symbol in the asymptotic
set that we will need is the ‘Ω’ which is the negation of ‘o’. That is to
say, ƒ(x) = Ω(g (x)) means that it is not true that ƒ(x) = o(g(x)). In the
study of algorithms for computers, the ‘Ω’ is used when we want to
express the thought that a certain calculation takes at least so-and-so
long to do. For instance, we can multiply together two n x n matrices in
time Ω (n3).
4.0 CONCLUSION
In this unit, you have learnt the five asymptotic symbols for representing
order of growth of algorithms. .
5.0 SUMMARY
This unit has explained the five functions for comparing the growth
order of an algorithm. These functions in ascending order are o, O,θ,∼,Ω
53
CIT 237 PROGRAMMING AND ALGORITHMS
www.eslearning.algorithm.com
www.personal.kent.edu/wmuhama/algorithms.
54
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Worst-Case
3.2 Best-Case
3.3 Average-Case
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit extends what we learnt in Unit1 of this module. It discusses the
different techniques that can be used to measure the efficiencies of
algorithms.
2.0 OBJECTIVES
• explain the three methods that are used to measure the efficiencies of
algorithms
• explain how to identify basic operations within an algorithm.
3.1Worst-Case
55
CIT 237 PROGRAMMING AND ALGORITHMS
We analyse the algorithm to see what kind of inputs yield the largest
value of the basic operations’ count C (n) among all possible inputs of
size n and then compute this worst-case value Cworst(n). Clearly, the
worst-case analysis provides very important information about an
algorithm’s efficiency by bounding its running time from above. In
other words, it guarantees that for any instance of size n, the running
time will not exceed Cworst(n), its running time on the worst-case inputs.
• An assignment
• A comparison between two variables
• An arithmetic operation between two variables. The worst-case
input is that input assignment for which the most basic operations
are performed.
Example 1
n := 5;
loop
get(m);
n := n -1;
until (m=0 or n=0)
Worst-case: 5 iterations
Example 2
get(n);
loop
get(m);
n := n -1;
until (m=0 or n=0)
Worst-case: n iterations
a. Sorting:
56
CIT 237 PROGRAMMING AND ALGORITHMS
c. Graph “searching”:
Example 5
57
CIT 237 PROGRAMMING AND ALGORITHMS
3.2 Best-Case
3.3 Average-Case
4.0 CONCLUSION
5.0 SUMMARY
58
CIT 237 PROGRAMMING AND ALGORITHMS
Write the pseudo codes for the algorithm to find the largest out of n
integers and use worst-case to determine the efficiency.
www.eslearning.algorithm.com
Levitin, A.( 2003 ). Introduction to the Design and Analysis of
Algorithms. Published by Addison- Wesley.
www.personal.kent.edu/wmuhama/algorithms.
59
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Basic Definitions
3.2 P and NP Problems
3.3 NP-Complete Problems
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
2.0 OBJECTIVES
60
CIT 237 PROGRAMMING AND ALGORITHMS
Are there decidable but intractable problems? Yes, there are, but the
number of known examples is small, especially of those that arise
61
CIT 237 PROGRAMMING AND ALGORITHMS
Traveling salesman: Find the shortest tour through n cities with known
positive integer distances between them (find the shortest Hamiltonian
circuit in a complete graph with positive integer weights).
Bin packing: Given n items whose sizes are positive rational numbers
not larger than 1, put them into the smallest number of bins of size 1.
Graph colouring: For a given graph, find its chromatic number (the
smallest number of colours that need to be assigned to the graph’s
vertices so that no two adjacent vertices are assigned the same colour.
62
CIT 237 PROGRAMMING AND ALGORITHMS
Most decision problems are in NP. First of all, this call includes all the
problems in P;
P ⊆ NP,
3.3NP-Complete Problems
63
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
5.0 SUMMARY
64
CIT 237 PROGRAMMING AND ALGORITHMS
www.eslearning.algorithm.com
www.personal.kent.edu/wmuhama/algorithms.
65
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Exercise
3.2 Solutions
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit presents another practical exercise in order for you to further
understand how to analyse efficiencies of algorithms.
2.0 OBJECTIVES
At the end of this unit, you should have had further understanding into
how to determine efficiency of algorithms.
3.0MAIN CONTENT
3.1 Exercise
Write the pseudocodes for the algorithm to find the average of the
smallest and the largest of n integers.
3.2Solution
MIN = A( I ) 1
For I = 1 to n
If MIN > A( I )
TEMP = MIN 4n
MIN = A( I )
A( I ) = TEMP
end If
end do
MAX = A( I )
For J = 2 to n 4n
If MAX < A( I )
TEMP1 = MAX 4n
MAX = A( J )
66
CIT 237 PROGRAMMING AND ALGORITHMS
A( J ) = TEMP
end If
end do
AVE = ( MIN + MAX ) / 2
PRINT AVE
= 1 * 4n * 4n * 1
4.0 CONCLUSION
5.0 SUMMARY
Write the pseudo codes of the algorithm to convert any binary number to
decimal and estimate the worse-case runtime efficiency.
www.eslearning.algorithm.com
www.personal.kent.edu/wmuhama/algorithms.
67
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Introduction to Sorting
3.2 Fundamentals of Divide-and-Conquer Algorithms
3.3 Practical Proof of Divided-and-Conquer Algorithms
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit discusses the meaning of sorting. It also describes the concept
of divide and conquer algorithms as problem-solving techniques.
2.0 OBJECTIVES
You are expected to be able to explain the following at the end of this
unit:
68
CIT 237 PROGRAMMING AND ALGORITHMS
• split this into several, smaller, sub-instances (of the same problem)
• independently solve each of the sub-instances
• and then combine the sub-instance solutions so as to yield a solution
for the original instance.
Problem of size n
subproblem 1 subproblem 2
of size n/2 of size n/2
solution to solution to
subproblem 1 subproblem 2
solution to the
original problem
69
CIT 237 PROGRAMMING AND ALGORITHMS
Let
But
= (3/4)(cn^2) + dn
So if
dn < (cn^2)/4 (i.e. d < cn/4)
then
In particular for all large enough n, (n > 4d/c = Constant), beta is faster
than alpha.
n > 4d/c
n/2 > 4d/c
...
n/2^i > 4d/c
70
CIT 237 PROGRAMMING AND ALGORITHMS
which suggests that using beta instead of alpha for the “solves these”
stage repeatedly until the sub-sub-sub..sub-instances are of size n0 < =
(4d/c) will yield a still faster algorithm.
cn^2 if n < = n0
T(gamma)(n) =
3T(gamma)( n/2 )+dn otherwise
4.0CONCLUSION
You should have understood sorting and what the divide and conquer
technique is all about.
5.0SUMMARY
71
CIT 237 PROGRAMMING AND ALGORITHMS
www.eslearning.algorithm.com
www.personal.kent.edu/wmuhama/algorithms.
http://mathworld.wolfram.com/QueensProblem.html
http://mathworld.wolfram.com/QueensProblem.html
72
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Understanding Merge Sort
3.2 The Merge Sort Algorithm
3.3 The Efficiency of the Merge Sort Algorithm
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit describes merge sort sorting technique. It explains merge sort
as an example of divide-and conquer algorithm.
2.0 OBJECTIVES
73
CIT 237 PROGRAMMING AND ALGORITHMS
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 6 7 8
The merging of two sorted arrays can be done as follows: Two pointers
(array indices) are initialised to point to the first elements of the arrays
being merged. Then the elements pointed to are compared and the
smaller of them is added to a new array being constructed; after that, the
index of that smaller element is incremented to point to its immediate
successor in the array it was copied from. This operation is continued
until one of the two given arrays is exhausted, and then the remaining
elements of the other array are copied to the end of the new array.
74
CIT 237 PROGRAMMING AND ALGORITHMS
The details of how this was arrived at will be studied in a future study in
Algorithm Design.
4.0CONCLUSION
The meaning and algorithm of merge sort has been presented. The
worse-case efficiency was also discussed.
5.0SUMMARY
75
CIT 237 PROGRAMMING AND ALGORITHMS
www.eslearning.algorithm.com
www.personal.kent.edu/wmuhama/algorithms.
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html..
76
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Introduction to Quick Sort
3.2 The Quick Sort Algorithm
3.3 The Efficiency of the Quick Sort Algorithm
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will be introduced to a new sorting technique called the
Quicksort which could be used in rearranging elements of any given
array.
2.0 OBJECTIVES
Obviously, after a partition has been achieved, A[s]s will be in its final
position in the sorted array, and we can continue sorting the two sub
77
CIT 237 PROGRAMMING AND ALGORITHMS
i j
P all are ≥p ≥p . . . ≤p all are≥
If the scanning indices have crossed over, i.e. I > I, we have partitioned
the array after exchanging the pivot with A[j]:
Finally, if the scanning indices stop while pointing to the same element,
i.e., I = j, the value they are pointing to must be equal to p (why?). Thus,
we have partitioned the array:
We can combined the last case with the case of crossed-over indices (I >
j) by exchanging the pivot with A[j] whenever I ≥ j.
78
CIT 237 PROGRAMMING AND ALGORITHMS
The details of how this was arrived at will be studied in the study in
Algorithm Design.
4.0 CONCLUSION
This unit has presented another type of sorting technique called the
quick sort technique which divides its important elements according to
their position or value to the array.
5.0 SUMMARY
79
CIT 237 PROGRAMMING AND ALGORITHMS
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
80
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Understanding Binary Search
3.2 The Algorithm
3.3 The Efficiency of Binary Search
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit introduces the binary search algorithm as well as its efficiency
and the procedures involved in traversing the elements of any given
array. The binary search is an effective way of traversing arrays.
2.0 OBJECTIVES
81
CIT 237 PROGRAMMING AND ALGORITHMS
3 14 27 31 39 42 55 70 74 81 85 93 98
Index 0 1 2 3 4 5 6 7 8 9 10 11
12
Value 3 14 27 31 39 42 55 70 74 81 85 93
98
Interation 1 l m r
Interation 2 l m r
Interation 3 l, m r
Cworst(n) ∈θ(log n)
Cbest(n) = 1
Cavg(n) =(log2 n)
82
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
5.0 SUMMARY
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
83
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Understanding Selection
3.2 The Algorithm
3.3 Efficiencies of Selection Sort
4.0 Conclusion
5.0 Summary
7.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit introduces you to the selection sort algorithm used in scanning
the all the given elements of an array to find its smallest element and
substitute it within the first element.
2.0 OBJECTIVES
We start selection sort by scanning the entire given list to find its
smallest element and exchange it with the first element, putting the
smallest element in its final position in the sorted list. Then we scan the
list, starting with the second element, to find the smallest among the last
n – 1 elements and exchange it with the second element, putting the
second smallest element in its final position. Generally, on the ith pass
through the list, which we number from 0 to n – 2, the algorithm
searches for the smallest item among the last n – I elements and swaps it
with Ai:
84
CIT 237 PROGRAMMING AND ALGORITHMS
As an example, the action of the algorithm on the list 89, 45, 68, 90, 29,
34, 17 is illustrated in figure
89 45 68 90 29 34 17
17 45 68 90 29 34 89
17 29 68 90 45 34 89
17 29 34 90 45 68 89
17 29 34 45 90 68 89
17 29 34 45 68 90 89
17 29 34 45 68 89 90
Figure: Selection sort’s operation on the list 89, 45, 69, 90, 29, 34, 17.
Each line corresponds to one iteration of the algorithm, i.e.,, a pass
through the list’s tail to the right of the vertical bar; an element in bold
indicates the smallest element found. Elements to the left of the vertical
bar are in their final positions and are not considered in this and
subsequent iterations.
85
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
5.0 SUMMARY
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
86
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Understanding Bubble Sort
3.2 The Algorithm
3.3 Efficiencies of Bubble Sort
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
The bubble sort is also another effective way in the variety of sort
techniques available in programming. It will be introduced in this unit as
well as its algorithm.
2.0 OBJECTIVES
87
CIT 237 PROGRAMMING AND ALGORITHMS
The action of the algorithm on the list 89, 45, 68, 90, 29, 34, 17 is
illustrated as an example.
Bubble Sort
89 45 68 90 29 34 17
45 89 68 90 29 34 17
45 68 89 90 29 34 17
45 68 89 29 90 34 17
45 68 89 29 34 90 17
45 68 89 29 34 17 |90
45 68 89 29 34 17 |90
45 68 29 89 34 17 |90
45 68 29 34 89 17 |90
45 68 29 34 17 89 90
etc
The first two passes of bubble sort on the list 89, 45, 68, 90, 29, 34, 17.
Note that a new line is shown after a swap of two elements is done. The
elements to the right of the vertical bar are in their final positions and
are not considered in subsequent iterations of the algorithm.
It is also in Θ(n2) in the worst and average cases. In fact, even among
elementary sorting methods, bubble sort is an inferior choice, and, if it
were not for its catchy name, you would probably never hear of it.
4.0 CONCLUSION
By now you should be able to use the bubble sort, having discovered
that it is a fast and easy way to transverse an array of any given set of
elements.
88
CIT 237 PROGRAMMING AND ALGORITHMS
5.0 SUMMARY
In the unit you have just concluded, the following were examined:
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
89
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Hill Climbing Technique
3.2 Knight-tour Problem
3.3 N-Queen Problems
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
This unit shows some special problems and algorithms. Hill climbing
can be used to solve problems that have many solutions, but where some
solutions are better than others.
2.0 OBJECTIVES
Hill climbing can be used to solve problems that have many solutions
but where some solutions are better than others. The algorithm is started
with a (bad) solution to the problem, and sequentially makes small
changes to the solution, each time improving it a little bit. At some point
the algorithm arrives at a point where it cannot see any improvement
anymore, at which point the algorithm terminates. Ideally, at that point a
90
CIT 237 PROGRAMMING AND ALGORITHMS
solution is found that is close to optimal, but it is not guaranteed that hill
climbing will ever come close to the optimal solution.
These problems are essentially the result of local maxima in the search
space - points which are better than any surrounding state, but which
aren't the solution . There are some ways in which we can get round
this (to some extent) by tweaking or extending the algorithm a bit. We
could use a limited amount of backtracking, so that we record alternative
reasonable looking paths which weren't taken and go back to them. Or
we could weaken the restriction that the next state has to be better by
looking ahead a bit in the search - maybe the next but one state should
be better than the current one. None of these solutions is perfect, and in
general hill climbing is only good for a limited class of problems where
we have an evaluation function that fairly accurately predicts the actual
distance to a solution.
a. Get the successors of the current state and use the `evaluation
function to assign a score to each successor.
b. If one of the successors has a better score than the current-state
then set the new current-state to be the successor with the best
score.
If one of the successors has a better score than the current state then set
the new current state to be the successor with the best score.
91
CIT 237 PROGRAMMING AND ALGORITHMS
Note that the algorithm does not attempt to exhaustively try every node
and path, so no node list or agenda is maintained - just the current state.
If there are loops in the search space then using hill climbing you
shouldn't encounter them - you can't keep going up and still get back to
where you were before.
92
CIT 237 PROGRAMMING AND ALGORITHMS
93
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
In this unit, you will observe that the hill climbing can be used to solve
problems that have many solutions but where some solutions are better
than others. An example of a problem that can be solved with hill
climbing is the travelling salesman problem. It is also used widely in
artificial intelligence fields for reaching a goal state from a starting
node.
5.0 SUMMARY
94
CIT 237 PROGRAMMING AND ALGORITHMS
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
Ahrens, W. ( 1910). Mathematische Unterhaltungen und Spiele.
Leipzig, Germany: Teubner, p. 381.
Conrad, A.; Hindrichs, T.; Morsy, H.; and Wegener, I.( 1994). "Solution
of the Knight's Hamiltonian Path Problem on Chessboards."
Discr. Appl. Math. 50, 125-134.
95
CIT 237 PROGRAMMING AND ALGORITHMS
96
CIT 237 PROGRAMMING AND ALGORITHMS
97
CIT 237 PROGRAMMING AND ALGORITHMS
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Problem I
3.2 Problem II
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Readings
1.0 INTRODUCTION
In this unit, you will be exposed to the practical applications of all the
sorting algorithms you learnt in the previous units of this course.
2.0 OBJECTIVES
3.1 Problem I
Solution
98
CIT 237 PROGRAMMING AND ALGORITHMS
numbers[j] = temp;
}
}
}
}
3.2 Problem II
Solution
l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
right--;
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
left++;
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
99
CIT 237 PROGRAMMING AND ALGORITHMS
4.0 CONCLUSION
This unit has showed you how to implement bubble sort using the C
codes. Also, it showed you how to execute the quick sort using the C
codes as well.
5.0 SUMMARY
• To implement the bubble and the quick sort using the C codes.
• To write programs using the C programming language.
1. Study the codes above and run them with sample data on a C
compiler.
2. Write the codes for implementing any sorting algorithm in
any programming language that you have learnt.
http://mathworld.wolfram.com/QueensProblem.html.
http://mathworld.wolfram.com/QueensProblem.html.
100