Sorting 2
Sorting 2
Rada Mihalcea
http://www.cs.unt.edu/~rada/CSCE3110
Sorting (II)
Reading: Chap.7, Weiss
Today…
• Quick Review
• Divide and Conquer paradigm
• Merge Sort
• Quick Sort
• Algorithm:
• Divide: If S has at leas two elements (nothing needs
to be done if S has zero or one elements), remove all
the elements from S and put them into two
sequences, S1 and S2, each containing about half of
the elements of S. (i.e. S1 contains the first ⎡n/2⎤
elements and S2 contains the remaining ⎣n/2⎦
elements.
• Recur: Recursive sort sequences S1 and S2.
• Conquer: Put back the elements into S by merging
the sorted sequences S1 and S2 into a unique sorted
sequence.
Merge-Sort Example
Running Time of Merge-Sort
A swap is performed when l is at an element larger than the pivot and r is at one
smaller than the pivot.
In Place Quick Sort (cont’d)
• General case:
• Time spent at level i in the tree is O(n)
• Running time: O(n) * O(height)
• Average case:
• O(n log n)
More Sorting Algorithms
• Bucket Sort
• Radix Sort
• Stable sort
• A sorting algorithm where the order of elements
having the same key is not changed in the final
sequence