Algorithms CSCI 235, Fall 2015 Lecture 12 Elementary Sorts II
Stability of an algorithm To show that an algorithm is not stable, it is sufficient to find an example for which the relative order of elements is not preserved during the sort. To show that an algorithm is stable may take more reasoning, because an unstable algorithm may preserve the relative order of elements for some initial orderings of an array but not others.
Bubble Sort Idea: On the every step of the algorithm, scan A from left to right and exchange adjacent elements that are out of order. Repeat until a scan finds no elements out of order. Invariant: After step i, (at least) the elements A[(n + 1 - i)..n] are in their final sorted positions.
Bubble sort pseudo-code Bubble-Sort(A) hi <- length[A] changed <- false repeat changed <- Bubble-Up(A, 1, hi) hi <- hi - 1 until not changed; Bubble-Up(A, lo, hi) for i <- lo to hi - 1 do if less(A[i + 1], A[i]) then swap(A, i, i+1); changed <- true return changed
Behavior of Bubble sort Is Bubble Sort stable? Try sorting: a b c d 2 1 2 1 Is Bubble Sort in place?
Running time of Bubble sort Bubble-Sort(A) hi <- length[A] changed <- false repeat changed <- Bubble-Up(A, 1, hi) hi <- hi - 1 until not changed; Bubble-Up(A, lo, hi) for i <- lo to hi - 1 do if less(A[i + 1], A[i]) then swap(A, i, i+1); changed <- true return changed T(n) = ? T2(n) = ? T(n) = ?
Merge Sort Idea: Recursively sort subarrays and then merge them into a single sorted array.
Pseudo code for Merge Sort Merge-Sort(A) MSort(A, 1, length[A]) MSort(A, lo, hi) if lo < hi then mid <- (lo + hi) div 2 MSort(A, lo, mid) MSort(A, mid + 1, hi) Merge(A, lo, mid, hi)
Merge pseudo-code Merge(A, lo, mid, hi) n <- (hi - lo) + 1 {Merge elements into temporary array B.} B <-newArray(n) left <- lo right <- mid + 1 for i = 1 to n do if left ≤ mid and (right > hi or less(A[left], A[right])) then B[i] <- A[left] left <- left + 1 else B[i] <- A[right] right <- right + 1 {Copy elements from B back to A} A[left] <- B[i]
Behavior of Merge Sort Is Merge Sort stable? Try sorting: a b c d 2 1 2 1 Is Merge Sort in place?
Running time of Merge Sort Derived in previous lectures: T(n) = 2T(n/2) + Cost of Merge Cost of Merge: (2 loops, each with maximum size of n) T2(n) = 2n = Q(n) Merge sort: T(n) = 2T(n/2) + n T(n) = Q(nlgn)
Summary Algorithm Stable In place Running time Insertion Yes Yes Selection Bubble Merge