Advanced Programming I Lecture Notes

Advanced Programming I Lecture Notes

1 February 2007 • Faster Sorting


Outline

Faster Sorting

a family portrait

  • The previous sorts were all O(n2).

    • Can we do better?

    • How much better can we do?

A Question Reasked

another question

Partitioning

partition(T a[], int left, int right)
  T pivot = a[left]
  int l = left + 1

  while l < right
    if (a[l] ≤ pivot) l++
    else if (pivot < a[right - 1]) right--
    else swap(a[l++], a[--right])

  swap(a[left], a[--l])
  return l

Quicksort


quicksort(T a[], int left, int right)

  if right > 1 + left
    int mid = partition(a, left, right)
    quicksort(a, left, mid)
    quicksort(a, mid + 1, right)

Quicksort Analysis

Oh Really?

quicksort on ints

quicksort on points

Well, No

Is It?

quicksort on sorted ints

quicksort on sorted points

Avoiding Worst-Case Behavior

Artful Pivot Choices

Do They Work?

clever pivot selection vs sorted ints

clever pivot selection vs sorted point

Rigorous Halving

Divide to Conquer

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)
  int len = aright - aleft
  if len > 1
    int h = len/2
    T * amid = aleft + h
    T * tmid = tleft + h

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

Performance

quicksort on sorted ints

quicksort on sorted points

Caveat Emptor

quicksort on sorted ints

quicksort on sorted points

Some Problems

The Big Idea

A Radix-10 Example

Radix Exchange Sort

Example Radix Exchange Sort

example radix exchange sort

Radix Exchange Sort


re-sort(int * left, int * right, int bit)

  // Place elements in [left, right) 
  // in increasing order.

  if left + 1 < right and bit < 32
    int * mid = partition(left, right, bit)
    re-sort(left, mid, bit + 1)
    re-sort(mid + 1, right, bit + 1)

Performance

Oh Really?

The Last Step

Requirements

Data Structures

Bucket Sort


This page last modified on 4 June 2006.

This work is covered by a
Creative Commons License.