Quick sort and Radix sort Rahul Sehgal rsehgal@cs.kent.edu
Rahul Sehgal, Kent State University Outline Comparison sort (quick sort) and execution example Linear sort (radix sort) and execution example Worst case situation for linear sort and quick sort. 12/9/2018 Rahul Sehgal, Kent State University
Comparison Sort (Quick Sort) Comparison sort: sorted order is determined based only on comparisons between the input elements. Quick sort: based on the divide-and-conquer paradigm. Process for sorting a typical sub-array A[p . . r]. Divide: Partition (rearrange) the array A[p . . r] into two (possibly empty) subarrays A[p . . q −1] and A[q +1 . . r] such that each element of A[p . . q −1] is less than or equal to A[q], which is, in turn, less than or equal to each element of A[q + 1 . . r]. 12/9/2018 Rahul Sehgal, Kent State University
Quick Sort: conquer and combine Conquer: Sort the two subarrays A[p . . q−1] and A[q +1 . . r] by recursive calls to quicksort. Combine: Since the subarrays are sorted in place, no work is needed to combine them: the entire array A[p . . r] is now sorted. 12/9/2018 Rahul Sehgal, Kent State University
Rahul Sehgal, Kent State University Quick sort- partition 2 8 7 1 3 5 6 4 r p j i 2 8 7 1 3 5 6 4 r p j i 2 8 7 1 3 5 6 4 r p i j 2 8 7 1 3 5 6 4 r p i j 2 1 7 8 3 5 6 4 r p i j 2 1 3 8 7 5 6 4 r p i j 2 1 3 4 7 5 6 8 r p 12/9/2018 Rahul Sehgal, Kent State University
Rahul Sehgal, Kent State University Quick sort- execution q 2 1 3 4 7 5 6 8 r p q 2 1 3 1 2 3 2 1 1 2 2 To sort an entire array A the initial call is QUICKSORT(A, 1, length[A]). 12/9/2018 Rahul Sehgal, Kent State University
Rahul Sehgal, Kent State University Quick sort- analysis The worst case for quick-sort occurs when the pivot is the unique minimum or maximum element, also known as one sided partition. Input elements sorted or reverse sorted. Worst case time: O(nᶺ2) Average case: O(nlogn) 12/9/2018 Rahul Sehgal, Kent State University
Linear sort (Radix sort) Linear sort: Any comparison sort algorithm takes Ω(nlogn) in the worst case to sort n elements. Can we do better? Yes, but we have to make assumptions that we have integers as input sequence which are in a small range (0 to k) or input is generated by a random process that distributes elements uniformly over the interval. We get deterministic about input. If k is large our runtime will increase. Radix sort: we do digit by digit sort. Starting from least significant digit. 12/9/2018 Rahul Sehgal, Kent State University
Radix sort- execution example Input sequence: 329, 457, 657, 839, 436,720,355 If digits are same we preserve order. 12/9/2018 Rahul Sehgal, Kent State University
Rahul Sehgal, Kent State University Radix sort - analysis We represent each element as a b-tuple of integers in the range [0, 1] and apply radix-sort with N = 2. Worst case O(bn) n # of elements (integers), each integer is b-bits long. Not good if range increases. 12/9/2018 Rahul Sehgal, Kent State University