COMP9024 ♢ Week 01b ♢Analysis of Algorithms ♢ (22T0)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [0/87]
❖ Analysis of Algorithms

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [1/87]
❖ Running Time

An algorithm is a step-by-step procedure

Most algorithms map input to output

[Diagram:Pic/runningTime.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [2/87]
❖ Empirical Analysis

  1. Write program that implements an algorithm
  2. Run program with inputs of varying size and composition
  3. Measure the actual running time
  4. Plot the results

[Diagram:Pic/experimental.png]

Limitations:

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [3/87]
❖ Theoretical Analysis

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [4/87]
❖ Pseudocode

Example: Find maximal element in an array

arrayMax(A):
|  Input  array A of n integers
|  Output maximum element of A
|
|  currentMax=A[0]
|  for all i=1..n-1 do
|  |  if A[i]>currentMax then
|  |     currentMax=A[i]
|  |  end if
|  end for
|  return currentMax

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [5/87]
❖ ... Pseudocode

Control flow

Function declaration Expressions
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [6/87]
❖ ... Pseudocode

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [7/87]
❖ Exercise : Pseudocode

Formulate the following verbal description in pseudocode:

To reverse the order of the elements on a stack S with the help of a queue:

  1. In the first phase, pop one element after the other from S and enqueue it in queue Q until the stack is empty.

  2. In the second phase, iteratively dequeue all the elements from Q and push them onto the stack.

As a result, all the elements are now in reversed order on S.

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [8/87]
Sample solution:

while S is not empty do
   pop e from S, enqueue e into Q
end while
while Q is not empty do
   dequeue e from Q, push e onto S
end while

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [9/87]
❖ Exercise : Pseudocode

Implement the following pseudocode instructions in C

  1. A is an array of ints

    ...
    swap A[i] and A[j]
    ...
    

  2. S is a stack

    ...
    swap the top two elements on S
    ...
    

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [10/87]
  1. int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
    

  2. x = StackPop(S);
    y = StackPop(S);
    StackPush(S, x);
    StackPush(S, y);
    


The following pseudocode instruction is problematic. Why?

...
swap the two elements at the front of queue Q
...

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [11/87]
❖ The Abstract RAM Model

RAM = Random Access Machine

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [12/87]
❖ Primitive Operations

Examples:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [13/87]
❖ Counting Primitive Operations

By inspecting the pseudocode …

Example:

arrayMax(A):
|  Input  array A of n integers
|  Output maximum element of A
|
|  currentMax=A[0]                   1
|  for all i=1..n-1 do               n+(n-1)
|  |  if A[i]>currentMax then        2(n-1)
|  |     currentMax=A[i]             n-1
|  |  end if
|  end for
|  return currentMax                 1
                                     -------
                             Total   5n-2

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [14/87]
❖ Estimating Running Times

Algorithm arrayMax requires 5n – 2 primitive operations in the worst case

Define: Let T(n) be worst-case time of arrayMax. Then

   a·(5n - 2) ≤ T(n)b·(5n - 2)

Hence, the running time T(n) is bound by two linear functions

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [15/87]
❖ ... Estimating Running Times

Seven commonly encountered functions for algorithm analysis

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [16/87]
❖ ... Estimating Running Times

In a log-log chart, the slope of the line corresponds to the growth rate of the function

[Diagram:Pic/growthFunctions.jpg]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [17/87]
❖ ... Estimating Running Times

The growth rate is not affected by constant factors or lower-order terms

[Diagram:Pic/constant.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [18/87]
❖ ... Estimating Running Times

Changing the hardware/software environment

Linear growth rate of the running time T(n) is an intrinsic property of algorithm arrayMax

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [19/87]
❖ Exercise : Estimating running times

Determine the number of primitive operations

matrixProduct(A,B):
|  Input  n×n matrices A, B
|  Output n×n matrix A·B
|
|  for all i=1..n do
|  |  for all j=1..n do
|  |  |  C[i,j]=0
|  |  |  for all k=1..n do
|  |  |     C[i,j]=C[i,j]+A[i,k]·B[k,j]
|  |  |  end for
|  |  end for
|  end for
|  return C

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [20/87]

matrixProduct(A,B):
|  Input  n×n matrices A, B
|  Output n×n matrix A·B
|
|  for all i=1..n do                     2n+1
|  |  for all j=1..n do                  n(2n+1)
|  |  |  C[i,j]=0                        n2
|  |  |  for all k=1..n do               n2(2n+1)
|  |  |     C[i,j]=C[i,j]+A[i,k]·B[k,j]  n3·4
|  |  |  end for
|  |  end for
|  end for
|  return C                              1
                                         ------------
                                 Total   6n3+4n2+3n+2

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [21/87]
❖ Big-Oh

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [22/87]
❖ Big-Oh Notation

Given functions f(n) and g(n), we say that

f(n) ∈ O(g(n))

if there are positive constants c and n0 such that

f(n) ≤ c·g(n)    ∀nn0
Hence: O(g(n)) is the set of all functions that do not grow faster than g(n)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [23/87]
❖ ... Big-Oh Notation

Example: function 2n + 10 is in O(n)

[Diagram:Pic/bigOh.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [24/87]
❖ ... Big-Oh Notation

Example: function n2 is not in O(n)

[Diagram:Pic/bigOh-2.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [25/87]
❖ Exercise : Big-Oh

Show that

  1. 7n-2 is in O(n)
  2. 3n3 + 20n2 + 5 is in O(n3)
  3. 3·log n + 5 is in O(log n)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [26/87]
  1. 7n-2 ∈ O(n)
    need c>0 and n0≥1 such that 7n-2 ≤ c·n for n≥n0
    ⇒  true for c=7 and n0=1
  2. 3n3 + 20n2 + 5 ∈ O(n3)
    need c>0 and n0≥1 such that 3n3+20n2+5 ≤ c·n3 for n≥n0
    ⇒  true for c=4 and n0=21
  3. 3·log n + 5 ∈ O(log n)
    need c>0 and n0≥1 such that 3·log n+5 ≤ c·log n for n≥n0
    ⇒  true for c=8 and n0=2
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [27/87]
❖ Big-Oh and Rate of Growth

f(n) ∈ O(g(n))g(n) ∈ O(f(n))
g(n) grows fasteryesno
f(n) grows fasternoyes
same order of growthyesyes
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [28/87]
❖ Big-Oh Rules

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [29/87]
❖ Exercise : Big-Oh

Show that   `sum_(i=1)^n i`   is O(n2)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [30/87]

`sum_(i=1)^ni = (n(n+1))/2 = (n^2+n)/2`

which is O(n2)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [31/87]
❖ Asymptotic Analysis of Algorithms

Asymptotic analysis of algorithms determines running time in big-Oh notation:

Example: Constant factors and lower-order terms eventually dropped
⇒ can disregard them when counting primitive operations
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [32/87]
❖ Example: Computing Prefix Averages


[Diagram:Pic/prefixAverage.jpg]

NB. computing the array A of prefix averages of another array X has applications in financial analysis

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [33/87]
❖ ... Example: Computing Prefix Averages

A quadratic algorithm to compute prefix averages:

prefixAverages1(X):
|  Input  array X of n integers
|  Output array A of prefix averages of X
|
|  for all i=0..n-1 do          O(n)
|  |  s=X[0]                    O(n)
|  |  for all j=1..i do         O(n2)
|  |     s=s+X[j]               O(n2)
|  |  end for
|  |  A[i]=s/(i+1)              O(n)
|  end for
|  return A                     O(1)

2·O(n2) + 3·O(n) + O(1) = O(n2)

Time complexity of algorithm prefixAverages1 is O(n2)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [34/87]
❖ ... Example: Computing Prefix Averages

The following algorithm computes prefix averages by keeping a running sum:

prefixAverages2(X):
|  Input  array X of n integers
|  Output array A of prefix averages of X
|
|  s=0
|  for all i=0..n-1 do          O(n)
|     s=s+X[i]                  O(n)
|     A[i]=s/(i+1)              O(n)
|  end for
|  return A                     O(1)

Thus, prefixAverages2 is O(n)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [35/87]
❖ Example: Binary Search

The following recursive algorithm searches for a value in a sorted array:

search(v,a,lo,hi):
|  Input  value v
|         array a[lo..hi] of values
|  Output true if v in a[lo..hi]
|         false otherwise
|
|  mid=(lo+hi)/2
|  if lo>hi then return false
|  if a[mid]=v then
|     return true
|  else if a[mid]<v then
|     return search(v,a,mid+1,hi)
|  else
|     return search(v,a,lo,mid-1)
|  end if

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [36/87]
❖ ... Example: Binary Search

Successful search for a value of 8:

[Diagram:Pic/binary-search-found.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [37/87]
❖ ... Example: Binary Search

Unsuccessful search for a value of 7:

[Diagram:Pic/binary-search-failed.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [38/87]
❖ ... Example: Binary Search

Cost analysis:

Thus, binary search is O(log2 n) or simply O(log n)   (why?)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [39/87]
❖ ... Example: Binary Search

Why logarithmic complexity is good:

[Diagram:Pic/log-complexity.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [40/87]
❖ Math Needed for Complexity Analysis

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [41/87]
❖ Exercise : Analysis of Algorithms

What is the complexity of the following algorithm?

enqueue(Q,Elem):
|  Input  queue Q, element Elem
|  Output Q with Elem added at the end
|
|  Q.top=Q.top+1
|  for all i=Q.top down to 1 do
|     Q[i]=Q[i-1]
|  end for
|  Q[0]=Elem
|  return Q

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [42/87]

Answer: O(|Q|)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [43/87]
❖ Exercise : Analysis of Algorithms

What is the complexity of the following algorithm?

binaryConversion(n):
|  Input  positive integer n
|  Output binary representation of n on a stack
|
|  create empty stack S
|  while n>0 do
|  |  push (n mod 2) onto S
|  |  n=n/2
|  end while
|  return S

Assume that creating a stack and pushing an element both are O(1) operations   ("constant")

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [44/87]

Answer: O(log n)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [45/87]
❖ Relatives of Big-Oh

big-Omega

big-Theta

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [46/87]
❖ ... Relatives of Big-Oh

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [47/87]
❖ ... Relatives of Big-Oh

Examples:

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [48/87]
❖ Complexity Analysis: Arrays vs. Linked Lists

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [49/87]
❖ Static/Dynamic Sequences

Previously we have used an array to implement a stack

The "fixed size" aspect is a potential problem: The rigid sequence is another problems:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [50/87]
❖ ... Static/Dynamic Sequences

Inserting a value (4) into a sorted array a with n elements:

[Diagram:Pic/arrayInsert.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [51/87]
❖ ... Static/Dynamic Sequences

Deleting a value (3) from a sorted array a with n elements:

[Diagram:Pic/arrayDelete.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [52/87]
❖ ... Static/Dynamic Sequences

The problems with using arrays can be solved by

[Diagram:Pic/linkedList.png]

Benefits:

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [53/87]
❖ Self-referential Structures

To realise a "chain of elements", need a node containing

To represent a chained (linked) list of nodes:

[Diagram:Pic/linkedList2.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [54/87]
❖ ... Self-referential Structures

Linked lists are more flexible than arrays:

Disadvantages:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [55/87]
❖ ... Self-referential Structures

Create a new list node:

makeNode(v)
|  Input  value v
|  Output new linked list node with value v
|
|  new.value=v      // initialise data
|  new.next=NULL    // initialise link to next node
|  return new       // return pointer to new node

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [56/87]
❖ Exercise : Creating a Linked List

Write pseudocode to create a linked list of three nodes with values 1, 42 and 9024.

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [57/87]

mylist=makeNode(1)
mylist.next=makeNode(42)
(mylist.next).next=makeNode(9024)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [58/87]
❖ Iteration over Linked Lists

When manipulating list elements

To iterate over a linked list:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [59/87]
❖ ... Iteration over Linked Lists

Standard method for scanning all elements in a linked list:

list  // pointer to first Node in list
p     // pointer to "current" Node in list

p=list
while p≠NULL do
|  … do something with p.value 
|  p=p.next
end while

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [60/87]
❖ ... Iteration over Linked Lists

[Diagram:Pic/listIterate1.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [61/87]
❖ ... Iteration over Linked Lists

[Diagram:Pic/listIterate2.png]

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [62/87]
❖ ... Iteration over Linked Lists

Check if list contains an element:

inLL(L,d):
|  Input  linked list L, value d
|  Output true if d in list, false otherwise
|
|  p=L
|  while p≠NULL do
|  |  if p.value=d then   // element found
|  |     return true
|  |  end if
|  |  p=p.next
|  end while
|  return false           // element not in list

Time complexity: O(|L|)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [63/87]
❖ ... Iteration over Linked Lists

Print all elements:

showLL(L):
|  Input linked list L
|
|  p=L
|  while p≠NULL do
|     print p.value
|     p=p.next
|  end while

Time complexity: O(|L|)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [64/87]
❖ Exercise : Traversing a linked list

What does this code do?

1  p=list
2  while p≠NULL do
3  |  print p.value
4  |  if p.next≠NULL then
5  |     p=p.next.next
6  |  else
7  |     p=NULL
8  |  end if
9  end while

What is the purpose of the conditional statement in line 4?

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [65/87]
Every second list element is printed.

If p happens to be the last element in the list, then p.next.next does not exist.
The if-statement ensures that we do not attempt to assign an undefined value to pointer p in line 5.

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [66/87]
❖ Exercise : Traversing a linked list

Rewrite showLL() as a recursive function.

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [67/87]

printLL(L):
|  Input linked list L
|
|  if L≠NULL do
|     print p.value
|     printLL(L.next)
|  end if

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [68/87]
❖ Modifying a Linked List

Insert a new element at the beginning:

insertLL(L,d):
|  Input  linked list L, value d
|  Output L with d prepended to the list
|
|  new=makeNode(d)  // create new list element
|  new.next=L       // link to beginning of list
|  return new       // new element is new head

Time complexity: O(1)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [69/87]
❖ ... Modifying a Linked List

Delete the first element:

deleteHead(L):
|  Input  non-empty linked list L, value d
|  Output L with head deleted
|
|  return L.next    // move to second element

Time complexity: O(1)


Delete a specific element (recursive version):

deleteLL(L,d):
|  Input  linked list L
|  Output L with element d deleted
|
|  if L=NULL then            // element not in list
|     return L
|  else if L.value=d then    // d found at front
|     return deleteHead(L)   // delete first element 
|  else                      // delete element in tail list
|     L.next=deleteLL(L.next,d)
|  end if
|  return L

Time complexity: O(|L|)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [70/87]
❖ Exercise : Implementing a Queue as a Linked List

Develop a datastructure for a queue based on linked lists such that …

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [71/87]
Use pointers to both ends

[Diagram:Pic/linkedListQueue.png]

Dequeue from the front …

dequeue(Q):
|  Input  non-empty queue Q
|  Output front element d, dequeued from Q
|
|  d=Q.front.value        // first element in the list
|  Q.front=Q.front.next   // move to second element
|  return d

Enqueue at the rear …

enqueue(Q,d):
|  Input queue Q
|
|  new=makeNode(d)     // create new list element      
|  Q.rear.next=new     // add to end of list
|  Q.rear=new          // link to new end of list

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [72/87]
❖ Comparison Array vs. Linked List

Complexity of operations, n elements

 arraylinked list
insert/delete at beginningO(n)O(1)
insert/delete at endO(n) O(1)
 
O(1)
("doubly-linked" list, with pointer to rear)
insert/delete at middleO(n)O(n)
find an elementO(n)
(O(log n), if array is sorted)
O(n)
 
index a specific elementO(1)O(n)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [73/87]
❖ Complexity Classes

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [74/87]
❖ Complexity Classes

Problems in Computer Science …

Classes of problems: Beware: NP stands for "nondeterministic, polynomial time (on a theoretical Turing Machine)"
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [75/87]
❖ ... Complexity Classes

Computer Science jargon for difficulty:

Computational complexity theory deals with different degrees of intractability
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [76/87]
❖ Generate and Test

In scenarios where

then a generate and test strategy can be used.

It is necessary that states are generated systematically

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [77/87]
❖ ... Generate and Test

Simple example: checking whether an integer n is prime

Generation is straightforward: Testing is also straightforward:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [78/87]
❖ ... Generate and Test

Function for primality checking:

isPrime(n):
|  Input  natural number n
|  Output true if n prime, false otherwise
|
|  for all i=2..n-1 do      // generate
|  |  if n mod i = 0 then   // test
|  |     return false       // i is a divisor => n is not prime
|  |  end if
|  end for
|  return true              // no divisor => n is prime

Complexity of isPrime is O(n)

Can be optimised: check only numbers between 2 and `|__sqrt n__|`     ⇒   O(`sqrt n`)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [79/87]
❖ Example: Subset Sum

Problem to solve ...

Is there a subset S of these numbers with Σx∈S x = 1000?

 34,  38,  39,  43,  55,  66,  67,  84,  85,  91,
101, 117, 128, 138, 165, 168, 169, 182, 184, 186,
234, 238, 241, 276, 279, 288, 386, 387, 388, 389

General problem:

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [80/87]
❖ ... Example: Subset Sum

Generate and test approach:

subsetsum(A,k):
|  Input  set A of n integers, target sum k
|  Output true if Σx∈Sx=k for some S⊆A
|         false otherwise
|
|  for each subset B⊆A do
|  |  if Σb∈Bb=k then
|  |     return true
|  |  end if
|  end for
|  return false

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [81/87]
❖ ... Example: Subset Sum

Given: a set of n distinct integers in an array A

A method to generate subsets:
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [82/87]
❖ ... Example: Subset Sum

Algorithm:

subsetsum1(A,k):
|  Input  set A of n integers, target sum k
|  Output true if Σx∈Sx=k for some S⊆A
|         false otherwise
|
|  for s=0..2n-1 do
|  |  if k = Σ(ith bit of s is 1) A[i] then
|  |     return true
|  |  end if
|  end for
|  return false

Obviously, subsetsum1 is O(2n)

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [83/87]
❖ ... Example: Subset Sum

Alternative approach …

subsetsum2(A,n,k)
(returns true if any subset of A[0..n-1] sums to k; returns false otherwise)

subsetsum2(A,n,k):
|  Input  array A, index n, target sum k
|  Output true if some subset of A[0..n-1] sums up to k
|         false otherwise
|
|  if k=0 then
|     return true   // empty set solves this
|  else if n=0 then
|     return false  // no elements => no sums
|  else
|     return subsetsum2(A,n-1,k-A[n-1]) or subsetsum2(A,n-1,k)
|  end if

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [84/87]
❖ ... Example: Subset Sum

Cost analysis:

Thus, subsetsum2 also is O(2n)
COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [85/87]
❖ ... Example: Subset Sum

Subset Sum is typical member of the class of NP-complete problems

COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [86/87]
❖ Summary


COMP9024 (22T0) ♢ Week 01b ♢ Analysis of Algorithms ♢ [87/87]


Produced: 20 Dec 2021