ALGORITHM DESIGN - Clive
ALGORITHM DESIGN - Clive
1.1 Algorithm
a) Definition
An algorithm is a collection of well defined instructions, designed to solve a problem. Algorithms are only as
good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined or An
algorithm is a finite sequence of instructions, an explicit, step-by-step procedure for solving a problem.
A common example of an algorithm would be instructions for assembling a model airplane. Given the starting set of
a number of marked pieces, one can follow the instructions given to result in a predictable end-state: the completed
airplane. Misprints in the instructions, or a failure to properly follow a step will result in a faulty end product.
2.1 Structured English: The English language can be used to write algorithms. The good thing with this
approach is that, the algorithms are easily understood by humans but unfortunately, not understood by the computer.
Below is an example of algorithm to find the average of a set of numbers.
Flow Chart: A flowchart is a graphical representation of a sequence of steps in an algorithm. In flow charts, symbols are used to
represent activities while arrows are used to represent the direction of activity through the processes. Typical examples of these
symbol include:
2. Process
1. Terminator
Terminator: The oval shape marks the Process: The rectangle represents
start or end point of a system or task. It a single action or step in an
usually contains “start” or “end” algorithm
3. Decision 4. Input/Output
Decision: The diamond Input/Output: The parallelogram
represents a decision or represents the information entering
branching point (eg If – Else) or leaving the system, eg customer
order (Input) or product (Output)
Start
Sum = Sum + N
Count = Count + 1
6. Flow Lines
Are they Yes
Flow Lines: The arrow indicates a sequence of
more N?
steps and the direction of floe
No
Average = Sum/Count End
Examples
Begin
Writeln(“ This is Cameroon”)
Writeln(“ I love very much”)
Writeln(“ What about you?”)
End.
b) Selection Construct or Conditional construct or Choice construct
This is a group of instructions designed in such a way as to permit the computer to make choice. The choice is
based on a condition. The computer is generally given two choices to make. One for a true, and the other for a
false condition. Examples include If-Then-Else, Case and GoTo statements.
If-Then-Else Statement
Activity 1
Begin
If x < 10 Then
Compiled by Sir Clive Ayumbi; [email protected] 675207337 3
Writeln(“ Passed”)
Else
Writeln(“Failed”)
End
A loop: is a sequence of statements which is specified once but which may be carried out several times in succession. The
code "inside" the loop is obeyed a specified number of times, or once for each of a collection of items, or until some
condition is met. In a flowchart a back arrow hints the presence of a loop.
A loop is represented by the while, for, repeat constructs in most programming languages. A loop can be bounded or
unbounded.
Unbounded loops refer to those whose number of iterations depends on the eventuality that the termination condition is
satisfied.
You must ensure that the condition for the termination of the looping must be satisfied after some finite number of
iterations, otherwise it ends up as an infinite loop. They are used in the following: ways.
Statement
We express 2
the above Until (Condition)
examples iteratively While (Condition)
Factorial(n)
for i := 1 to n do
begin
factorial := factorial * n;
i = i+1
end;
Consider the following example for calculating the summation, which we will denote as sum(n), meaning n + n-1 + n-2 +
n-3 + ... + 2 + 1 + 0. Hence, sum(5) = 5+4+3+2+1+0 = 15. Now we will write psuedo-code to calculate the sum(n) using
Iteration.
total = 0; i = i + 1;
Recursion: In simple terms recursion is when a function calls itself. That is, in the course of the function definition
there is a call to that very same function.
Function definition:
Function factorial(n)
The sum function which sums the integer from 1 to n, where n is to be given.
Function sum(n)
F3 = F2 +F1
F4 = F3 + F2
F5 = F4 + F3
Exercise: write a recursive function to generate the elements in the Fibonacci sequence.
INSERTION_SORT (A)
Begin
For j ← 2 To length[A] Do
Key ← A[j]
Begin
Put A[j] into the sorted sequence A[1 . . j − 1]
End
i←j−1
While i > 0 and A[i] > key Do
A[i +1] ← A[i]
i←i−1
A[i + 1] ← key
End
The figure above shows the operation of INSERTION-SORT on the array A= (5, 2, 4, 6, 1, 3). Each
part shows what happens for a particular iteration with the value of j indicated. j indexes the "current
card" (or number) being inserted into the “hand”( or left side of the array). Elements to the left of A[j]
that are greater than A[j] move one position to the right, and A[j] moves into the evacuated position.
Example 2: Using insertion sort, sort the word ASORTINGEXAMPLE in ascending order.
A S O R T I N G E X A M P L E
A S O R T I N G E X A M P L E
A O S R T I N G E X A M P L E
A O R S T I N G E X A M P L E
A O R S T I N G E X A M P L E
A I O R S T N G E X A M P L E
A I N O R S T G E X A M P L E
A G I N O R S T E X A M P L E
A E G I N O R S T X A M P L E
A E G I N O R S T X A M P L E
A A E G I N O R S T X M P L E
A A E G I M N O R S T X P L E
A A E G I M N O P R S T X L E
A A E G I L M N O P R S T X E
B) Bubble Sort
Bubble Sort is an elementary sorting algorithm. It works by repeatedly exchanging adjacent
elements, if necessary. When no exchanges are required, the file (or array) is sorted. In bubble sort,
we keep passing through the file, exchanging adjacent elements that are out of order, continuing until
the file is sorted. Bubble sort is slower than insertion sort and selection sort. When the minimum
element is encountered during the first pass, we exchange it with each of the elements to its left,
eventually putting it at the leftmost position.
Pseudocode for a Bubble Sort Algorithm
Begin
For i ← 1 to length [A] Do
For j ← length [A] down to i +1 Do
If A[A] < A[j-1] Then
Exchange A[j] ↔ A[j-1]
End
5 2 4 6 1 3 2 5 4 6 1 3
2 4 5 6 1 3 2 4 5 1 6 3
2 4 1 5 6 3 2 1 4 5 6 3
1 2 4 5 6 3 1 2 4 5 3 6
1 2 4 3 5 6 1 2 3 4 5 6
From the figure notice how the elements are interchange as one moves from left to
right and top to down.
Example 2: Using bubble sort, sort the word ASORTINGEXAMPLE in ascending order.
A S O R T I N G E X A M P L E
A O S R T I N G E X A M P L E
A O R S T I N G E X A M P L E
A O R S T I N G E X A M P L E
A O R S I T N G E X A M P L E
A O R I S T N G E X A M P L E
A O I R S T N G E X A M P L E
A I O R S T N G E X A M P L E
A I O R S N T G E X A M P L E
A I O R N S T G E X A M P L E
A I O N R S T G E X A M P L E
A I N O R S T G E X A M P L E
A I N O R S G T E X A M P L E
A I N O R G S T E X A M P L E
A I N O G R S T E X A M P L E
Example 1 : Using selection sort, sort the word ASORTINGEXAMPLE in ascending order.
A S O R T I N G E X A M P L E
A S O R T I N G E X A M P L E
A A O R T I N G E X S M P L E
A A E R T I N G O X S M P L E
A A E E T I N G O X S M P L R
A A E E G I N T O X S M P L R
A A E E G I N T O X S M P L R
A A E E G I L T O X S M P N R
A A E E G I L M O X S T P N R
A A E E G I L M N X S T P O R
A A E E G I L M N O S T P X R
A A E E G I L M N O P T S X R
A A E E G I L M N O P R S X T
A A E E G I L M N O P R S X T
A A E E G I L M N O P R S T X
A A E E G I L M N O P R S T X
b) Deadlock
When two algorithms are in a deadlock, if they cannot continue their execution. This
happens when the resource needed by one to complete execution, is needed also by another
with the same priority.
c) Lovelock
Lovelock is a situation in which two algorithms enter an infinite loop because they keep on
exchanging resources. This usually happens when the output of algorithm A serves as input
for algorithm B and vice visa.
6.0 Testing, Evaluation and Analysis of algorithms
After an algorithm is written or designed it must be tested to ensure correctness.
6.1 Testing
Testing an algorithm is done by first performing a dry run. That is running the mentally. If it
runs mentally without any error, then it can now be tested with some sample data in a real
system. An algorithm that runs successfully to the end does not mean it is correct. It can run
without errors yet solving a different problem.
6.2 Evaluation
6.3 Analysis
After testing and evaluating an algorithm we might discover that, though it solves the problem
for which it was designed, it might be doing so at the expense of system resources such as
memory space and processor time. If this is the case, the algorithm is said to be working but not
effective. Analysis an algorithm entails checking to ensure correctness, reasonableness and
effectiveness.
ALGORITHM C Code
i = 1; {
while i is not greater than n, printf(“Enter the last number you want to sum to \n”);
i = i + 1; {
return 0;
scanf("%f",&num1);
printf("Enter num2");
scanf("%f",&num2);
printf("Enter num3");
scanf("%f",&num3);
printf("Enter num4");
scanf("%f",&num4);
printf("Enter num5");
scanf("%f",&num5);
sum= num1+num2+num3+num4+num5;
return 0;
Algorithm to calculate the average of n /*program assigns numbers into a five-element float array, and
numbers computes the sum and average*/
#define N 5
int main(void) {
int i;
a[0] = 56.5; a[1] = 67.5; a[2] = 45; a[3] = 89; a[4] = 78;
sum += a[i];
average = sum/N;
return 0;
Constant: Π= 3.14
Output: Area {
Take Π=3.14
Calculate the area using Area= Π*r*r printf("Enter the radius of a circle \n");
/* read in radius */
/* area formula */
/* print results */
stop if (a < 6)
printf("%d + %d = %d\n",n,i,n+i);
else
Output: Area printf(“Enter the value for the Length of the rectangle\n”);
scanf(“%d”, &L);
Calculate the area using Area=l*w printf(“Then Area %d = %d x %d”, Area, L, W);
Stop }
Output: Area printf(“Enter the value for the Base of the Triangle\n”);
scanf(“%d”, &B);
Calculate the area using Area=b*h/2 printf(“Then Area %d = %d x %d”, Area, B, H);
Stop. }
Input: an integer, x
Output f
Start
Give an integer, x
Stop
Analysis
Give an integer, x.
f ( x) 2 x 2 2 x 3
Output: f (x )
Start
Give an integer, x
For x=1 to 5 do
Begin
f ( x) 2 x 2 2 x 3
Output: f (x )
End
{
Analysis
int c, n, fact = 1;
Input: integer n
printf("Enter a number to calculate it's factorial\n");
Processing: if n<2 then n!=1
Else n!=n*(n-1)!
scanf("%d", &n);
Output: n!
for (c = 1; c <= n; c++)
fact = fact * c;
Start
printf("Factorial of %d = %d\n", n, fact);
Give an integer n
return 0;
Set fac to 1
}
For i=n down to 1 do
Print fac
Stop.
//#include<conio.h>
Analysis
#include<math.h>
Input: a, b, c with a<>0
Process: D b 4 * a * c
2
//#include<process.h>
X2 = (-b-D)/2
Output: X1, X2 {
double a,b,c,d,root1,root2,t;
Start
Give 3 integers a, b, c
Else
Calculate D from D b 4 * a * c printf("\n\n- To solve the equation ,please provide the value of a, b & c -");
2
If D<0 then output “Roots are not real” prinf(“ Note The value of a is never zero\n”);
scanf("%lf", &c);
d=(b*b-4*a*c);
t = pow(d,0.5);
if(d<0)
root1=(-b+t)/(2.0*a);
root2=(-b-t)/(2.0*a);
printf("\n The roots of the quadratic equation are %lf & %lf", root1,root2);
return 0;
a+b
This is called infix notation, because the operator (“+”) is inside the expression
A problem is that we need parentheses or precedence rules to handle more complicated expressions:
For Example :
a+b*c = (a + b) * c ?
= a + (b * c) ?
How ?
Infix notation : a + b
Prefix notation : + a b
Postfix notation: a b +
Prefix notation was introduced by the Polish logician Lukasiewicz, and is sometimes called “Polish notation”.
Question: Why would anyone ever want to use anything so “unnatural,” when infix seems to work just fine?
Answer: With postfix and prefix notations, parentheses are no longer needed!
(a + b) * c ab+c* *+abc
a + (b * c) abc*+ +a*bc
x+y
(x + y) - z
w * ((x + y) - z)
(2 * a) / ((a + b) * (a - c))
3r-
13r-+
st*13r-++
vwxyz*-+*