Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithms CSCI 235, Fall 2015 Lecture 12 Elementary Sorts II

Similar presentations


Presentation on theme: "Algorithms CSCI 235, Fall 2015 Lecture 12 Elementary Sorts II"— Presentation transcript:

1 Algorithms CSCI 235, Fall 2015 Lecture 12 Elementary Sorts II

2 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.

3 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 i)..n] are in their final sorted positions.

4 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

5 Behavior of Bubble sort
Is Bubble Sort stable? Try sorting: a b c d Is Bubble Sort in place?

6 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) = ?

7 Merge Sort Idea: Recursively sort subarrays and then merge them into a single sorted array.

8 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)

9 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]

10 Behavior of Merge Sort Is Merge Sort stable? Try sorting: a b c d
Is Merge Sort in place?

11 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)

12 Summary Algorithm Stable In place Running time Insertion Yes Yes
Selection Bubble Merge


Download ppt "Algorithms CSCI 235, Fall 2015 Lecture 12 Elementary Sorts II"

Similar presentations


Ads by Google