Tutorial 2

Adgenda

Recursion

Alt text

One recrusion call to deal with LHS, one to deal with RHS

Requires:

Analysing recursive functions

  1. Count the operations in a single recursive step
  2. Express the algorithm as a mathematical recurrence
  3. Compute a bound for the recurrence by expanding the recursive calls or drawing the recursion tree.
    • Will try with both methods

Selection sort example:

if n > 1 then maxindex <- 0 # O(1) for i <- 1 to n-1, do if A[i] > A[maxIndex] then #o(4n) maxindex <- i swap(A[maxIndex], A[n-1]) #O(1)

T(n)={O(1)if n=1O(1)+T(n1)if n>1 T(n) = \begin{cases} O(1) & \text{if } n = 1\\ O(1) + T(n-1) & \text{if } n > 1 \end{cases}

Use the fact that 1+2+3+...+(n1)+n=n(n1)/21+2+3+...+(n-1)+n = n(n-1)/2 to conclude T(n)T(n) is (O(n^{2}))

Binary Search Summary

T(n)={O(1)if n=0O(1)+T(n/2)if x>0 T(n) = \begin{cases} O(1) & \text{if } n = 0\\ O(1) + T(n/2) & \text{if } x > 0 \end{cases}

Sorting - Selection sort

How it works:

Insertion sort

How it works:

procedure insertionSort(A: list of sortable items) for i = 1 to length(A) - 1 do currentElement = A[i] j = i - 1 while j >= 0 and A[j] > currentElement do A[j + 1] = A[j] j = j - 1 A[j + 1] = currentElement end for end procedure

Merge sort

Quick sort

Run time:

Alt text

Tutorial sheet

Questions 1, 2, 6.

Question 1

  1. 210=O(c)2^{10} = O(c)
  2. 2log3(log3n)=O(log(logn))2\log _{3} (\log _{3} n) = O(\log (\log n))
  3. 100log2n100 \log _{2} n
  4. 4n=O(n)4n = O(n)
  5. 4nlog4n+2n=O(n)4n \log_{4}n + 2n = O(n)
  6. 2log2n=n=O(n)2 ^{\log _{2} n} = n = O(n)
  7. n2+10n=O(n2)n^{2} + 10n = O(n^{2})
  8. n2log2(n)=n2log(n)n^{2} \log _{2} (n) = n^{2} \log (n)
  9. n3=O(n3)n^{3} = O(n^{3})
  10. 2n=O(2n)2^{n} = O(2^{n})

Question 2:

Question 3:

Question 6

T(n)={1if n=13T(n/2)+2if n>1 T(n) = \begin{cases} 1 & \text{if } n = 1\\ 3T(n/2) + 2 & \text{if } n > 1 \end{cases}

Question 9

for x in range (A, length) a = A[x] b = B[x]

Similar process to Binary search. Have A, B, and x as input

for j in range (A, length) if BinarySearch(sortedB, A[j] - x) return true #This is done in log n time return false

Run time: $n(\log n + \log n) = 2n(\log n) = O(n \log n)