CS333 - Problem Solving and Object Oriented Programming in
C++
[ Home | Schedule
| Personal
Progress | Search | Glossary | Help
]
Simple Explanation | Big O analysis |
Advanced Explanation |
DESCRIPTION |
|
||||||||||||||||||||
EXAMPLES Click here for more examples |
// constant time algorithm - getting "i-th" element from an array // same time regardless of size of array answer = a[ i ]; // linear time algorithm - finding an element in an unordered list (either linked list of array) // we show th array algorithm here - problem: find the location of the element whose value is "value" // in general, doubling the size of the list will double the time to find the element // (assuming it has equal probability of being anywhere in the list) for(int i = 0; i < SIZE_ARRAY; i++) if(a[i] == value) { // found it !! - do something and break out of loop break; } /* logarithmic algorithm: searching an ordered list. (for details see
binary search algorithm) you would be considered slightly eccentric if you searched a
telephone book for a number by starting on page 1 and reading every name until you found
the one you are looking for. A classic guessing game that also uses the binary search algorithm is number guessing. You think of a number between let's say 1 and 32., I will guess 16 and you will tell me if I am low or high. If you guess is too low, then I know that the numbers from 1 to 16 are out - in other words I can throw away half the problem. Then I will guess a number halfway between 17 and 32 - 25. If you say too high, then I know the answer is between 16 and 25. Now I only have 1/4 the list to guess in. Every guess reduces the remaining list in half. 32 is 2**5 (2 raised to the 5th power. one guess leaves a list of 16 = 2 **4 elements,
two guesses leaves a list of 8 = 2**3. Now double the range of numbers 1 to 64. How much harder is the problem? Not much. In one guess I reduce the size of the list to 32 elements and I am back to the same size problem I had before. 64 = 2**6, so at most 6 guesses. Why is it called logarithmic? well the logarithm to the base 2 of 32 is 5 and the logarithm to the base 2 of 64 is 6. So if the size of the problem is "n", then log(n) is the number of steps. to guess a number between 1 and 64,000 takes at most 16 guesses since 2**16 = 65576 */ /* quadratic algorithm - simple sorts are the most common example but you can make a simple quadratic algorithm with nested loops as shown in this example */ for(int i = 0; i < n; i++) for(int j = 0; j < n; i++) { // statements here will run "n**2" (or n*n) times longer as :"n" is doubled } |
||||||||||||||||||||
TIPS |
|