Divide and Conquer: CS 306 Lecture notes

Computer Algorithms II Lecture Notes

2 December 2008 • Divide and Conquer


Outline

  • Using Dividing

  • What Division Does

  • Divide and Conquer

  • Analysis

  • Recursion

  • Mergesort

caesar

Looking For x

unsigned ls-find(a[], n, x)

  for i = 1 to n
    if a[i] = x
      return i

  return 0

Quickly Looking For x

unsigned bs-find(a[], n, x)
  l = 0
  r = n + 1
  while l < r
    m = (l + r)/2
    if a[m] = x
      return m
    if a[m] < x
      l = m + 1
    else
      r = m
  return 0

Comparison

Dividing Find

unsigned d-find(a[], l, r, x)
  if l + 1 = r
    return a[l] = x ? l : 0
  m = (l + r)/2
  i = d-find(a, l, m, x)
  return i == 0 ? d-find(a, m, r, x) : i

dividing non-sorted find

  • There's not enough information to do better.

  • The correct subsolution is the ultimate solution.

Finding Min and Max

min-max(a[], n)

  min = max = a[1]
  for i = 2 to n
    if min > a[i]
      min = a[i]
    else if max < a[i]
      max = a[i]

  return min, max

Using Dividing

min-max(a[], l, r)

  if l + 2 = r
    if a[l] < a[l + 1]
      return a[l], a[l + 1]
    else
      return a[l + 1], a[l]

  m = (l + r)/2
  mn1, mx1 = min-max(a, l, m)
  mn2, mx2 = min-max(a, m, r)

  return mn1 < mn2 ? mn1 : mn2,
         mx1 < mx2 ? mx2 : mx1

divided min-max

  • min-max() uses 3/2n + 1 comparisons.

What Division Does

Divide and Conquer

Analysis

Recursion

find(a[], n, x)
  m = n/2
  if a[m] = x
    return true
  if a[m] < x
    return find(a + m, m, x)
  return find(a, m, x)

find(a[], n, x)
  if n = 0
    return false
  if a[0] = x
    return true
  return 
    find(a[1..n-1], n - 1, x)

Dividing to Sort

a data segment

  • Given a data segment,

a data segment

  • divide it into halves.

Reuniting Divisions

Merging

  • Scan from left to right, copying the minimum value.

    merging sorted subsequences

merge(T * 
   tl, tr, al, am, ar)
 T * s = am
 while tl < tr
  if (al < am) ∧
     (s == ar or *al < *s)
   *tl++ = *al++
  else
   *tl++ = *s++

Mergesort

mergesort(T * aleft, aright, tleft, tright)

  len = aright - aleft

  if len > 1
    mid = len/2
    T * amid = aleft + mid
    T * tmid = tleft + mid

    mergesort(aleft, amid, tleft, tmid)
    mergesort(amid, aright, tmid, tright)
    merge(
      tleft, tright, aleft, amid, aright)

Analysis

Array Merging

a data segment

The orignal data segment

a data segment

is split in place into halves.

a data segment

The subsegments occupy the segment they're supposed to merge into.

Array Mergesort

Linked-List Dividing

Summary

References

Credits


This page last modified on 27 November 2008.

Creative
    Commons License