Computer-Science

Sorting

Contents

0. Sorting so far…

(1) PQ-sort

(2) Selection-sort

(3) Insertion-sort

(4) Heap-sort

Summary of Sorting Algorithms

스크린샷 2021-12-14 오후 10 22 03

1. Merge-Sort

Divide-and-Conquer

Merge-Sort

Algorithm mergeSort(S, C)
  Input sequence S with n
    elements, comparator C
  Output sequence S sorted
    according to C
  if S.size() > 1
    (S1, S2)  partition(S, n/2)
    mergeSort(S1, C)
    mergeSort(S2, C)
  else:
    S  merge(S1, S2)

Merging Two Sorted Sequences

Algorithm merge(A, B)
  Input sequences A and B with n/2 elements each
  Output sorted sequence of A È B

  S  empty sequence
  while (not A.empty()) and (not B.empty())
    if A.front() < B.front()
      S.addBack(A.front());
      A.eraseFront();
    else
      S.addBack(B.front());
      B.eraseFront();

  while not A.empty()
    S.addBack(A.front());
    A.eraseFront();

  while not B.empty()
    S.addBack(B.front());
    B.eraseFront();

  return S

Merge-Sort Tree

스크린샷 2021-12-15 오전 1 55 38

Execution Example

ezgif com-gif-maker

Analysis of Merge-Sort

스크린샷 2021-12-15 오전 2 14 47

Summary of Sorting Algorithms

스크린샷 2021-12-15 오전 2 15 17

2. Quick-Sort

스크린샷 2021-12-15 오전 2 20 39

Partition

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, respectively

  L, E, G  empty sequences
  x  S.erase(p)

  while not S.empty()
    y  S.eraseFront()
    if y < x
      L.insertBack(y)
    else if y = x
      E.insertBack(y)
    else // y > x
      G.insertBack(y)
  return L, E, G

Quick-Sort Tree

스크린샷 2021-12-15 오전 2 26 23

Execution Example

ezgif com-gif-maker (1)

Worst-case Running Time

스크린샷 2021-12-15 오전 2 30 13

Expected Running Time

스크린샷 2021-12-15 오전 2 31 52

스크린샷 2021-12-15 오전 2 34 24

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 l >= r
    return
  i  a random integer between l and r
  x  S.elemAtRank(i)
  (h, k)  inPlacePartition(x)
  inPlaceQuickSort(S, l, h - 1)
  inPlaceQuickSort(S, k + 1, r)

In-Place Partitioning

Example

ezgif com-gif-maker (2)

Summary of Sorting Algorithms

스크린샷 2021-12-15 오전 2 44 55