Docsity

Discrete Structures: Recursive Algorithms and Sorting Techniques, Study notes of Discrete Structures and Graph Theory

Partial preview of the text

Download Discrete Structures: Recursive Algorithms and Sorting Techniques and more Study notes Discrete Structures and Graph Theory in PDF only on Docsity!

CS 173: Discrete Structures

Eric Shaffer

Office Hour: Wed. 1-2, 2215 SC

[email protected]

Review

  • What does it mean to say f(x) is order g(x)?
  • Recursive algorithms:
    • We looked at functions we can compute recursively
    • We described the time complexity of these functions
      • Using what?

Insertion sort… Time for an animation: http://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html

Create your own recursive algorithm!

How about computing n

2

recursively?

Can we express n

2

in terms of (n-1)

2

What recurrence relation describes the running time?

Tower of Hanoi… The Tower of Hanoi invented by French mathematician, Edouard Lucas, in 1883. TH (A, B, C,n)

  1. If n = 1 then Move(A,B)
  2. else
  3. TH(A,C,B,n-1)
  4. Move(A,B)
  5. TH(C,B,A,n-1)

Towers of Hanoi efficiency (or lack thereof) Now let’s analyze the running time. T(n) = 2 T(n-1) + C Unroll a bit… = 2 (2 T(n-2) + C) + C = 4 T(n-2) + 3C = 4 (2 T(n-3) + C) + 3C = 8 T(n-3) + 7C … = 2 k T(n-k) + ( k -1)C What is k when this bottoms out at 1?

T(1) = C

n- T(1) + ( n- -1)C = ( n -1) C = O( n ) More general techniques investigated in a couple weeks

Recursive sorting…. MergeSort (list)

  1. If |list| = 1 then return list
  2. else
  3. MergeSort(left half of list)
  4. MergeSort(right half of list)
  5. Merge(left half of list,right half of list)

Recursive sorting…. MergeSort (list)

  1. If |list| = 1 then return list
  2. else
  3. MergeSort(left half of list)
  4. MergeSort(right half of list)
  5. Merge(left half of list,right half of list) Animations: http://www.cse.iitk.ac.in/users/dsrkg/cs210/applets/sortingII/mergeSort/mergeSort.html http://vision.bc.edu/~dmartin/teaching/sorting/anim-html/insertion.html

Merge sort Write down the recurrence relation: T(n) = 2 T(n/2) + cn We’ll talk about techniques for solving it later.

When is recursion inefficient? Recursive function for computing the nth Fibonacci number: Iterative function for computing the nth Fibonacci number: Which of these is better?