Sunday, September 29, 2013

Measure Algorithms, Master Theorem and Example Algorithms

When algorithms are considered it is not logical to make the best case as a base since it only in the space of possibilities it only consumes one possibility which is not enough to consider the performance of an algorithm concerning the best case.

The crucial point is to make asymptotic analysis of the software performance. It is possible to make it happen by ignoring the dependencies on the external boundaries like cpu, ram etc.
Another issue is to consider the growth of the running time instead of actual running time. 

Consider a case that there exists two algorithms whose complexities are n3 and n2. It doesn't really depend on the environment that these algorithms, the result is always n2 beats the n3 algorithm.

Divide and Conquer Approach:

First of all we need to consider the "Recursion" to define D&A clearly.
Recursion is a way of solving big problems by using "proof by induction". In proof by induction as we know it there exists 2 steps. To clarify:
  1. The basis (base case): prove that the statement holds for the first natural number n. Usually, n = 0 or n = 1.
  2. The inductive step: prove that, if the statement holds for some natural number n, then the statement holds for n + 1.

If "proof by induction" is clear for a programmer then recursion is very easy to understand.

Recursion can be applied when the bigger problem can be reduced to identical smaller problems.

D&C is one of the major algorithm design techniques in the paradigm. The logic behind D&C is to divide the bigger problem into smaller problems. There are 3 phases to be achieved to make it possible to use this approach:
* Divide : Define sub-problems whose combination makes the whole problem
* Conquer : Each sub-problem is a problem to be solved(this is the part where recursion is used)
* Combine : Combine the sub-problems to find the complete solution to the problem.

Master Theorem:

When recursion is considered, we divide the problem into pieces with the count of a and each sub-problem consumes n/b time.
Pseudocode :

function T( n )
   if n < 1 then return
   T(n/b)
   T(n/b)
   ...
   T(n/b)

Algorithms such as above can be represented as a recurrence relation:
T(n) = aT(n/b) + f(n)
where n is the size of the problem.

This theorem is called the Master Theorem and it simplifies our calculation of O.
There exist 3 cases for the Master Theorem:
1) if
      f(n) = \Theta\left( n^{c} \right)
   then
      T(n) = \Theta\left( n^{\log_b a} \right)
2) if
      f(n) = \Theta\left( n^{c} \log^{k} n \right)
    then
      T(n) = \Theta\left( n^{c} \log^{k+1} n \right)
3) if
      f(n) = \Theta\left( n^{c} \right)
    then
      T\left(n \right) = \Theta\left(f(n) \right) 

  • a is the number of sub-problems in the recursion. 
  • n/b is the size of each sub-problem(assumption is that every sub-problem is considered in the same complexity). 
  • f(n) being amount of work done outside the recursive calls.

Some Algorithms:

Sort Algorithms:

Input: a sequence of variables
Output: a permutation of variables that are computed with the comparison operation. The comparison operation can be defined in a specific way which only requires to return true or false when two parameters are given.

Insertion Sort:

Assume the comparison is executed with op(x,y) so insertion sort algorithm is basically:
for  j <- 2 to n
   do key <- A[j]
        i <- j - 1
        while i > 0 and op(A[i],key)
               do A[i+1] <- A[i]
                    i <- i -1
        A[i+1] <- key

assumptions : the list is assumed to be divided into two parts. The beginning part is declared as it is already sorted.
As a result of the assumption, we start with the second element in the list and check the comparison operator when the value that is contained inside keys neighbor with the key it returns true or false. When true, we require to switch the first parameter with the second and continue until the operator returns false.

Merge Sort:

Merge sort sort algorithm is basically:
Merge sort A[1,n]
If n = 1 done
     Recursively sort A[1, n/2] and A[[n/2]+1, n]
Merge two sets

The merging of the two lists starts by comparing the first elements in both of the lists(op(n/2,n)). When the comparison is done the next parameter to be taken is from the same list whose index is increased by one.
The asymptotic analysis of the algorithm is n since we execute the operation only once for each element.
If we consider the algorithms analysis for each row, we have:
 T(n)
 O(1)
 2T(n/2)
 O(n)
So our formula is divided into two:
if n = 1
    then we have O(1)
if n > 1
    then we have 2T(n/2) + O(n)

The first case is constant so we can omit this value.
When calculating the recursion, don't forget that we have the list divided into two and give to Merge Sort this half list, our asymptotic analysis gives us the n/4. As expected recursion ends up with a constant where n=1 as in our first case of our formula.
So we need to know the level of the tree that we have found to solve the recursion. The height of the tree is log(n).
With these values our complexity is calculated as O(n*log(n)) + O(n) which leads to O(n*log(n))

Quick Sort:

Quicksort algorithm is based on recursion. The starting point of quicksort is to select a pivot and making the left side of the pivot smaller than itself and right side to larger according to the comparison operator.

Pseudocode:
A is the set of variables
p is the pivot
q is the size of the list

Partition(A,p,q)
  x <- A[p]
  i <- p
  for j <- p+1 to q
     do if A[j] <= x
            then i <- i + 1
                 switch A[i] <-> A[j]
  switch A[p] <-> A[i]
  return i

QuickSort(A,p,q)
  if p < q
     then r <- Partition(A,p,q)
     QuickSort(A,p,r-1)
     QuickSort(A,p,r+1)

The Quicksort algorithms complexity is O(nlog(n)).

Decision Tree Sort:

There is a method to solve the sorting problem using decision trees.
Assume we have a binary tree that is composed of ai and aj where a1≤a2 for each node.
See below image for an example:

The formal definition of the binary decision tree is:
Given inputs as <a1,a2,...an>each node has the value ai,aj where aπ(i)≤aπ(j).(To include when there is an equality of comparison left child has the precedence.)
Left child is navigated when the comparison operation is true and right child is navigated when false.
Each leaf is composed of the permutation of <π(1),π(2)..π(n)> such that aπ(1)≤aπ(2)≤...≤aπ(n)

When the list is used for the given inputs considered by pair the leaf node that we achieved is the permutation of our input list that is sorted.

Although this is a useful way it is not practical when we consider we need all the permutations of the list with size n. Since our output will also be n in the below permutation we need to use k = n
\frac{n!}{(n-k)!}.
which is equal to n!
Assuming we have the tree of height h, this implies that number of leaves is 2h.
As a result the algorithms complexity is Ω(nlog(n)).

Counting Sort:

Counting sort is not a comparison based sorting algorithm. The key issue about this algorithm is that it is defined inside the numbers domain and the comparison operation is static defined by mathematical <.
Pseudocode :

countingsort(A[], B[], k)
Step1
            for i = 1 to k do
               C[i] = 0
Step2
            for j = 1 to length(A) do
               C[A[j]] = C[A[j]] + 1
Step3
            for 2 = 1 to k do
               C[i] = C[i] + C[i-1]
Step4
            for j = 1 to length(A) do
               B[C[A[j]]] = A[j]
               C[A[j]] = C[A[j]] - 1

A is the input list
B is the output list
k is the biggest element of A
Example : 1, 6, 7, 4, 3, 9 with k = 9
In step 1 : 
C[] = [0,0,0,0,0,0,0,0,0]
In step 2 :
C[] = [1,0,1,1,0,1,1,0,1]
In step 3 :
C[]= [1,1,2,3,3,4,5,5,6]
In step 4:
A[6] -> B[6]
A[5] -> B[2]
A[4] -> B[3]
A[3] -> B[5]
A[2] -> B[4]
A[1] -> B[1]
B[] = [A[1],A[5],A[4],A[2],A[3],A[6]]

The complexity is O(k+n) and if k is big the algorithms performance is not good. If k < n then it is a good algorithm to use.

Other Algorithms:

Binary Search:

Binary Search is a good way to practice Divide and Conquer approach with recursion.
What we have in the beginning is, we have an array sorted of variables and we would like to insert a new variable according to the comparison operator(op(x,y)). Lets use our 3 steps for D&C:
  1. Divide : compare the input,x, with the middle element in the array, as a side effect the array is divided into two since it is sorted.
  2. Conquer : recursively execute the Divide with the array which is proper to use with the comparison operators returning value. Stop when there exists no sub array on the side the algorithm leads to. This is the place to put the x.
  3. Combine : trivial

When we consider the asymptotic analysis the O:
T(n) = T(n/2) + O((1)
        = O(logn)

Power of a Number:

Lets solve the powering a number problem with recursion:

There exists two solutions:
1) Lets go back to our "proof by induction" way of thinking.

  • We know that  x0 is 1. 
  • We know that x1 = x
  • Lets assume xn and try to find out what is  xn+1
    • To implement  xn+1 we will use the two premisses we have x1 and xn
    • xn+1  = x1 * xn
So if we use this method to implement our function:
function power(x,n)
If n = 0
    return 1;
else
    return x * (power(x,n-1));

When we consider the complexity O(n) is our result.


Second solution is only a modification on the previous one. We just need to change the 2nd line and divide it into two:
function power(x,n)
If n = 0 return 1;
if n is even
    return power(x,n/2) * power(x,n/2)
if n is odd
    return  power(x,(n-1)/2) * power(x,(n-1)/2) * x;

When the complexity is considered the result is O(logn), which is pretty better than the O(n).
MIT - Introduction to Algorithms

No comments:

Post a Comment