Zen-like algorithms

A simpler algorithm may sometimes be more challenging to find, but consider the benefits.

Simple algorithms are:

  • easier to understand
  • easier to implement
  • easier to verify and debug
  • easier to maintain
  • more compact
  • more efficient
  • more fun

For example, consider the following snippets of code to to find the maximum value between three numbers, x, y , and z.

if (x < y)
    if (x < z)
        min = x;
    else 
        min = z;
else
    if (y < z)
        min = y;
    else
        min = z;

It doesn’t seem that complex, however the code could be easier to understand. Let’s try something else:

if (x < y && x < z)
    min = x;
else if (y < z)
    min = y;
else 
    min = z;

This is simpler of course, but is there another, even simpler, Zen-like way to code the algorithm:

min = x;
if (y < min)
    min = y;
if (z < min)
    min = z;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s