Monday, 9 May 2011

Algorithms

An algorithm is a description of the steps required to complete a process.  Algorithms are often used by computers, but are in fact independent of them and programming languages.  In algorithms there are three types of activity known as the three 'constructs': the first being sequence (instructions in a certain order), the next being selection (deciding between values), and the last repetition until a criteria is met.  With all algorithms the inputs, outputs and variables are critical to know before an algorithm is created.
  Algorithms can be expressed in five ways.  The first of these is using structured English - therefore English with regular syntax, secondly Pseudo Code which is a way of expressing the steps that a computer program would take but is independent of all programming languages, thirdly as a flowchart using the steps in the previous two types, fourthly through using hand tracing in a table to show how the variables change as the algorithm is conducted, and lastly in a programming language so that the algorithm can be executed by a computer.  Flowcharts involve using decision boxes for selection, process boxes for sequence, and using these with arrows in the right way for repetition.

As an example here is an algorithm that finds the letter 'A' in a list of letters and indicates when it has been found.

Structured English

  • Input Text
  • Count equals 1
  • TextLength equals the  length of the string Text
  • Repeat until Count is greater than the number of characters in Text
  1. If the character at position Count in the string equals 'A', print 'Found it!'
  2. Else add 1.
  • If Count exceeds TextLength then print 'Character Not Found'


Pseudo Code

  • Count ← 1
  • Input Text
  • TextLength ← Text.length
  • For each character in Text
  1. If Character = 'A'  print 'Found it'
  2. Else Count = Count + 1
  • If Count > TextLength print 'Character Not Found'


Flowchart


Hand trace table
This trace table shows what happens to each value as it is used with the algorithm.

Input
Value
Character = A
Count
Text Length
Output
LA
L
No
1
2


A
Yes
2

Found it!

No comments:

Post a Comment