Data Structures & Algorithms Lecture Notes

20 April 2010 • 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

Sorting Again

Sorting With A Heap

Heapsort

heapsort(a[], n)

  for i = 1 to n - 1
    bubble-up(a, i)

  for i = n - 1 to 1
    swap(a[0], a[i])
    bubble-down(i)

Are They?

heapsort vs quicksort on ints

heapsort vs quicksort on 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 array [], int left, int right, int bit)

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

Performance

Oh Really?

The Last Step

Requirements

Data Structures

Bucket Sort

References


This page last modified on 15 April 2010.

Creative
    Commons License