12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 3.9 Space Bounds 85A classic example of a space/time tradeoff is the lookup table. A lookup tablepre-s<strong>to</strong>res the value of a function that would otherwise be computed each time it isneeded. For example, 12! is the greatest value for the fac<strong>to</strong>rial function that can bes<strong>to</strong>red in a 32-bit int variable. If you are writing a program that often computesfac<strong>to</strong>rials, it is likely <strong>to</strong> be much more time efficient <strong>to</strong> simply pre-compute the 12s<strong>to</strong>rable values in a table. Whenever the program needs the value of n! for n ≤ 12,it can simply check the lookup table. (If n > 12, the value is <strong>to</strong>o large <strong>to</strong> s<strong>to</strong>re asan int variable anyway.) Compared <strong>to</strong> the time required <strong>to</strong> compute fac<strong>to</strong>rials, itmay be well worth the small amount of additional space needed <strong>to</strong> s<strong>to</strong>re the lookuptable.Lookup tables can also s<strong>to</strong>re approximations for an expensive function such assine or cosine. If you compute this function only for exact degrees or are willing<strong>to</strong> approximate the answer with the value for the nearest degree, then a lookuptable s<strong>to</strong>ring the computation for exact degrees can be used instead of repeatedlycomputing the sine function. Note that initially building the lookup table requiresa certain amount of time. Your application must use the lookup table often enough<strong>to</strong> make this initialization worthwhile.Another example of the space/time tradeoff is typical of what a programmermight encounter when trying <strong>to</strong> optimize space. Here is a simple code fragment forsorting an array of integers. We assume that this is a special case where there are nintegers whose values are a permutation of the integers from 0 <strong>to</strong> n − 1. This is anexample of a Binsort, which is discussed in Section 7.7. Binsort assigns each value<strong>to</strong> an array position corresponding <strong>to</strong> its value.for (i=0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!