Algorithm Analysis


1. Complexity of Algorithms


2. Running Time Calculations


3. Logarithmic Growth

iteration value of  i
(at the top of loop)
number of times
line 4 is executed
1 n 1
2 n/21 1
3 n/22 1
k n/2k-1 = 1 1
k+1 n/2k = 0 0
(loop not executed)

We are interested in what k is (because that's the number of times the line 4 is executed).  In other words,

T(n) = 1 + 1 + 1 + .. + 1  = (k * 1)
          |<-- k of them--->|

To derive k, we look at the relation at the last iteration (kth):



So, T(n) = log2n + 1   (where log2n is alternatively written as lgn).


4. Big-Oh (O) Notation

In this course, we only cover the Big-Oh.  For the example above, we have:

    T(n) = 60n2 + 5n + 1 = O(n2)


5. Search algorithms

  1. Linear search in an unsorted (or any) sequence

    Problem: finding an element in an array of size n
    Input: key, array A = [x1, x2,…, xn], n
    Output: the index of key in A, (0 if key is not in the list)

    Program find_key( key, A, n )
    1. index := 1
    2. while index <= n
    3.   begin
    4.   if key = A[index] then   // count this comparison
    5.     return index
    6.   index := index + 1
    7.   end
    8. return 0
    end find_key
  1. Binary Search -- for a sorted list (in the ascending order)

    Example:  Search for 16

     

    Problem: find an element in a sorted list (whose index is 0 through n-1)
    Input: key, L a list and n
    Output: The index of key in L, -1 otherwise

    procedure BinarySearch(key, L, n)
    1.  low := 0 
    2.  high := n-1
    3.  while (low <= high) do
    4.    begin
    5.    mid = floor((low + high)/2)
    6.    if (key = L[mid]) then        // count this comparison
    7.      return mid
    8.    else if (key < L[mid]) then 
    9.      high := mid - 1
    10.   else 
    11.     low := mid + 1
    12.   end
    13. return -1    // key not found (fall through)
    end BinarySearch