Download Notes on Algorithmic Cost and Complexity | COP 3502 and more Study notes Computer Science in PDF only on Docsity!
Algorithmic Cost and Complexity
There are two aspects of algorithmic performance:
- Time
- Instructions take time.
- How fast does the algorithm perform?
- What affects its runtime?
- Space
- Data structures take space
- What kind of data structures can be used?
- How does choice of data structure affect the
runtime?
Measuring Performance
For example: A simple calculator :
Perform the four basic arithmetic functions:
- Addition
- Subtraction
- Multiplication
- Division
Prompt the user for:
- Operand 1
- Operand 2
- Operator
Algorithm Calculator
double op1 // 1st operand op2 // 2nd operand answer ; // result char operator ; // operator
// obtain operands and operator from user printf( “Enter the first operand: ” ); scanf(“%lf”, &op1 ); printf( “Enter the second operand: ” ); scanf(“%lf”, &op2 ); printf( “Enter the operator: ” ); scanf(“%c”, &operator );
// perform the calculation if ( operator == ‘+’ ) answer = op1 + op2;
if ( operator == ‘-’ ) answer = op1 - op2;
if ( operator == ‘*’ ) answer = op1 * op2;
if ( operator == ‘/’ ) answer = op1 / op2;
printf( “The answer is %f \n”, answer );
// end algorithm Calculator
Analyzing Work Done
How many operations does Calculator do?
- read/write pairs (to obtain data)
- Testing conditionals
- Branching
- Performing operation
- Assigning variables
Note :
We will ignore the read/write instructions. They deal with
the world “outside the algorithm” and involve factors
beyond what we care about here.
Measures of Work
(ignoring read/write pairs)
Addition - four tests (@ 2 each)
- one add
- one assignment
- total: 10
- What’s the worst case?
Division - four tests (@ 2 each)
- one divide
- one assignment
- total: 10
- What’s the average (expected) case?
- 10
Algorithm Analysis: Loops
Consider the following nested loops (LOOP1 and LOOP2) intended to sum each of the rows in an NxN two dimensional array, storing the row sums in a one-dimensional array rows and the overall total in grandTotal.
LOOP 1:
grandTotal = 0; for (k=0; k<n-1; ++k) rows[k] = 0; for (j = 0; j <n-1; ++j){ rows[k] = rows[k] + matrix[k][j]; grandTotal = grandTotal + matrix[k][j]; } }
LOOP 2:
grandTotal =0; for (k=0; k<n-1; ++k) rows[k] = 0; for (j = 0; j <n-1; ++j) rows[k] = rows[k] + matrix[k][j]; grandTotal = grandTotal + rows[k]; }
- What is the number of addition operations? 2N
2
versus
N^2 + N
- Assuming we’re working with a hypothetical computer
that requires 1 microsecond to perform an addition, for N
= 1000, loop 1 would take 2 sec., loop 2 would require
just over 1 second. (For N= 100,000 time would be
approx. 6 hrs and 3 hours respectively)
Big-O Notation
- It is a method of algorithm classification.
Definition: Suppose there exists a function f(n) defined on
nonnegative integers such that the number of operations
required by an algorithm for an input size n is less than or
equal to some constant c times f(n) (i.e. c*f(n)) for all but
finitely many n.
That is, the number of operations is at worst proportional to
f(n) for all large values of n.
Such an algorithm is said to be an O[ f(n) ] algorithm.
- Loop 1 and Loop 2 are both in the same big-O category:
O(N^2 )
Example 1:
Use big-O notation to analyze the time efficiency of the
following fragment of C code:
for(k = 1; k <= n/2; k++) { . . for (j = 1; j <= nn; j++) { . . } }*
Since these loops are nested, the efficiency is n^3 /2 , or O( n^3 )
in big-O terms.
Thus, for two loops with O[ f 1 (n) ] and O[ f 2 (n) ] efficiencies,
the efficiency of the nesting of these two loops is
O[ f 1 (n) * f 2 (n) ].
Example 2:
Use big-O notation to analyze the time efficiency of the
following fragment of C code:
for (k=1; k<=n/2; k++) { . . } for (j = 1; j <= nn; j++) { . . }*
The number of operations executed by these loops is the
sum of the individual loop efficiencies. Hence, the
efficiency is n/2+n^2 , or O( n^2 ) in big-O terms.
Thus, for two loops with O[ f 1 (n) ] and O[ f 2 (n) ] efficiencies,
the efficiency of the sequencing of these two loops is
O[ fD(n) ] where fD(n) is the dominant of the functions f 1 (n)
and f 2 (n).
Complexity of Linear Search
In measuring performance, we are generally concerned
with how the amount of work varies with the data.
Consider, for example, the task of searching a list to see if
it contains a particular value.
- A useful search algorithm should be general.
- Work done varies with the size of the list
- What can we say about the work done for list of any length?
i = 0;
while (i < MAX && this_array[i] != target) i = i + 1;
if (i <MAX) printf ( “Yes, target is there \n” ); else printf( “No, target isn’t there \n” );
Order Notation
How much work to find the target in a list containing N
elements?
Note : we care here only about the growth rate of work.
Thus, we toss out all constant values.
Best Case - It’s the first value
“order 1,” O(1)
Worst Case - It’s the last value, N
“order N,” O(N)
Average - N/2 (if value is present)
“order N,” O(N)
- Best Case work is constant ; it does not grow with the
size of the list.
- Worst and Average Cases work is proportional to the
size of the list, N.
Order Notation
O(1) or “Order One”:
- does not mean that it takes only one operation
- does mean that the work doesn’t change as N changes
- is a notation for “constant work”
O(N) or “Order N”:
- does not mean that it takes N operations
- does mean that the work changes in a way that is
proportional to N
- is a notation for “work grows at a linear rate ”
Improving on Linear Search
Can we do better?
Array of the Social Security Numbers of all students in this
class.
Index is the Social Security Number.
Results is O(1), but wastes HUGE space
Data Structures and Complexity
- Can we assume that data are:
- sorted and
- stored in an appropriate sized array?
#define MAX 30
int array[MAX];
- (^) Still... we need to know what N is in advance to
declare an Array.
- Binary Search Tree (BST) can be very valuable, if
N is not predictable. A BST allows O(log N)
search performance if certain conditions are met:
The tree must be full and balanced.
Data Structures and Complexity
Traverse Search Insert
Linked List (unsorted) N N 1
Linked List (sorted) N N N
Array (unsorted) N N 1
Array(sorted) N log N N
Binary Tree N N log N
BST N log N log N
Insertion = cost to find location + cost of insertion.
Bubblesort Revisited
Bubblesort works by comparing and swapping values
in a list
23 78 45 8 32 56
23 78 45 8 32 56
23 78 45 8 32 56
23 78 8 45 32 56
23 8 78 45 32 56
8 23 78 45 32 56
Complexity of Bubblesort
How many comparisons will the inner loop do?
(N-1) + (N-2) + (N-3) + ... + 1
Average: N/2 for each “pass”
How many “passes” (outer loop) are there?
N – 1
Tossing constants:
- Each loop involves O(N) work
- Inner will be executed for each iteration of outer
So what is the complexity?
O(N) * O(N) = O(N^2 )
Complexity of MergeSort
Merge sort requires O(N log 2 N) comparisons.
The reasoning:
All the merge operations across any given level of the
trace diagram will require O(N) comparisons. There
are log 2 N levels. Hence, the overall efficiency is
O(N log 2 N).
In level 1: There is one merge operation. We’re
merging 2 lists with size N/2.
In level 2: There are two merge operations. We’re
merging 2 pairs of lists with size N/4.
In the last level (i.e. level log 2 N): There are N/
merge operations. We’re merging N/2 pairs of lists
with size 1.
How much work is involved in each level?
- Each of the N numerical values is compared or
copied during each level
- (^) Therefore, the work for each level is O (N)
Thus the total for MergeSort is:
O(log N) * O (N) = O(NlogN)
Example Problems
1. Algorithm A runs in O(N^2 ) time, and for an input size of 4,
the algorithm runs in 10 milliseconds, how long can you
expect it to take to run on an input size of 16?
2. Algorithm A runs in O(log 2 N) time, and for an input size of
16, the algorithm runs in 28 milliseconds, how long can you
expect it to take to run on an input size of 64?
- Algorithm A runs in O(N^3 ) time. For an input size of 10, the algorithm runs in 7 milliseconds. For another input size, the algorithm takes 189 milliseconds. What was that input size?
- For an O(Nk) algorithm, where k is a positive rational number, a friend tells you that instance of size M took 16 seconds to run. You run an instance of size 4M and find that it takes 256 seconds to run. What is the value of k?
- Algorithm A runs in O(N^3 ) time and Algorithm B solves the same problem in O(N^2 ) time. If algorithm A takes 5 milliseconds to complete for an input size of 10, and algorithm B takes 20 milliseconds for an input size of 10, what is the input size that you expect the two algorithms to perform about the same?
- For an O(N^3 ) algorithm, an instance with N = 512 takes 56 milliseconds. If you used a different-sized data instance and it took 7 milliseconds how large must that instance be?
Answers
1. Algorithm A runs in O(N^2 ) time, and for an input size of 4,
the algorithm runs in 10 milliseconds, how long can you
expect it to take to run on an input size of 16?
----- = ------- => x =160ms 10ms x
2. Algorithm A runs in O(log 2 N) time, and for an input size of
16, the algorithm runs in 28 milliseconds, how long can you
expect it to take to run on an input size of 64?
log 16 log ------------ = ------------ => x =42 ms 28 ms x
- Algorithm A runs in O(N^3 ) time. For an input size of 10, the algorithm runs in 7 milliseconds. For another input size, the algorithm takes 189 milliseconds. What was that input size?
103 N^3 ----- = ------- => N = 30 7 ms 189
- For an O(Nk) algorithm, where k is a positive rational number, a friend tells you that instance of size M took 16 seconds to run. You run an instance of size 4M and find that it takes 256 seconds to run. What is the value of k?
Mk^ (4M)k^256 ------- = ---------- => 4 k^ = -------- => k = 2 16 ms 256 16
- Algorithm A runs in O(N^3 ) time and Algorithm B solves the same problem in O(N^2 ) time. If algorithm A takes 5 milliseconds to complete for an input size of 10, and algorithm B takes 20 milliseconds for an input size of 10, what is the input size that you expect the two algorithms to perform about the same? For algorithm A: O(N^3 ) means execution time <= c1 * N^3 for N = 10 execution time is 5ms = c1 * 10^3 so , c1 = 5 / 10^3
For algorithm B: O(N^2 ) means execution time <= c2 * N^3 for N = 10 execution time is 20 ms = c2 * 10^2 so , c2 = 20 / 10^2
what is N for which c1 * N^3 = c2 * N^2
Substitute for c1 and c2: 5 / 10^3 * N^3 = 20 / 10^2 * N^2 => N = 40