Chapter 10: Sorting, Sets, and Selection

10.1 Merge-Sort

10.1.1 Divide-and-Conquer
MergeSort.pdf 3
Using Divide-and-Conquer for Sorting
MergeSort.pdf 4
10.1.2 A C++ Implementation of Merge-Sort
html-10.2 (MergeSort)

mergesort.cpp

10.2 The Set ADT

10.2.1 A Simple Set Implementation
Sets.pdf 3
Using a Sorted Sequence to Implement a Set
Generic Merging as a Template Method Pattern
html-10.4a (Merger1)
html-10.4b (Merger2)

Using Inheritance to Derive Set Operations
html-10.5a (UnionMerger)
html-10.5b (IntersectMerger)
html-10.5c (SubtractMerger)


10.3 Quick-Sort

High-Level Description of Quick-Sort
QuickSort.pdf 3-12

  • Quick-sort is a randomized sorting algorithm based on the divide-and-conquer paradigm:
    • Divide: pick a random element x (called pivot) and partition S into
    • L elements less than x
    • E elements equal x
    • G elements greater than x
    • Recur: sort L and G
    • Conquer: join L, E and G

Algorithm partition(S, p)
Input sequence S, position p of pivot
Output subsequences L, E, G of the elements of S less than, equal to, or greater than the pivot, resp.
L, E, G ← empty sequences
xS.remove(p)
while ¬S.isEmpty()
     yS.remove(S.first())
     if y < x
          L.insertLast(y)
     else if y = x
          E.insertLast(y)
     else { y > x }
         G.insertLast(y)
return L, E, G

10.3.1 In-Place Quick-Sort


Algorithm inPlaceQuickSort(S, l, r)
   Input: sequence S, ranks l and r
   Output: sequence S with the elements of rank between l and r rearranged in increasing order
   if lr
       return
   i a random integer between l and r
   xS.elemAtRank(i)
   (h, k) ← inPlacePartition(x)
   inPlaceQuickSort(S, l, h − 1)
   inPlaceQuickSort(S, k + 1, r)

html-10.7 (QuickSort)

qsort.cpp

Running Time of Quick-Sort
QuickSort.pdf 13-15



10.3.2 Randomized Quick-Sort





10.4 A Lower Bound on Comparison-Based Sorting

SortingLowerBound.pdf 1-5


10.5 Bucket-Sort and Radix-Sort

10.5.1 Bucket-Sort
RadixSort.pdf  2

Stable Sorting

10.5.2 Radix-Sort
RadixSort.pdf  7



10.6 Comparison of Sorting Algorithms

QuickSort.pdf 18

Algorithm Time
  • Notes
insertion-sort
selection-sort
bubble-sort

O(n2)
  • in-place
  • slow (good for small inputs)
quick-sort O(n2) worst case and O(n log n) in average
  • in-place, randomized
  • fastest (good for large inputs)
heap-sort O(n log n)
  • in-place
  • fast (good for large inputs)
merge-sort O(n log n)
  • sequential data access
  • fast (good for huge inputs)
bucket-sort
radix-sort
O(n)
  • the keys are integers in the range [0, N −1]
  • fast (good for huge inputs)