Algorithm: Definition

An algorithm is not a snazzy tune that Al Gore dances to.  It’s a set of logic whose purpose is to perform some function or result in a calculated value.  For example, the following C# code is an algorithm for finding the position of the first “a” in a string of text given to it:

Code Snippet

  1.         public int FindFirstA(string text)
  2.         {
  3.             for(int x = 0; x < text.Length; x++)
  4.                 if (text[x] == ‘A’)
  5.                     return x;
  6.             return -1;
  7.         }

This code is not the most efficient, since there are better ways to accomplish this, but it demonstrates a simple algorithm.  It takes a line of text (called a string) the loops through each character (letter) in the string, one by one, comparing it to the letter ‘A’ until it finds it.  When it finds it, it stops looking and returns the position at which it found it.  If it reaches the end without finding it, it returns a –1, indicating that it was not found.

Algorithms do not have to be computer code.  A simple list of directions to a friend’s house is also an algorithm.  Algorithms can be incredibly complex too, such as the calculations used in the government defense supercomputers that calculate how a nuclear bomb explodes.  Pretty much anything that follows a definite set of logical steps is an algorithm.

Leave a Reply