80 likes | 317 Views
More Sorting. Radix Sort Relies on a stable sorting algorithm (for example counting sort). Radix Sort. Sort an array of numbers Example: { 329, 457, 657, 839, 436, 720, 355 } If we look the digits for any number (ones, tens, hundreds), they are between 0 and 9. Radix Sort.
E N D
More Sorting Radix SortRelies on a stable sorting algorithm (for example counting sort)
Radix Sort • Sort an array of numbers • Example: { 329, 457, 657, 839, 436, 720, 355 } • If we look the digits for any number (ones, tens, hundreds), they are between 0 and 9
Radix Sort • An y digit is between 0 and 9 • that sets up well for using counting sort (with k = 9) one digit at a time
Radix Sort • Strategy: • Step 1: Sort numbers based on ones digit • Step 2: Sort numbers based on tens digit • Step 3: Sort numbers based on hundreds digit • ….continue if necessary
Radix Sort • Using a stable sorting algorithm is important: • If we did not and we have, after sorting on 1s: • 456 • 457 • When we sort on 10s (they both have a 5), they could end up inverted
Radix Sort • Running time analysis: • Number of numbers to sort = n • Number of digits per number = d • If we have numbers with different numbers of digits, take the biggest as the standard, pad the other ones with 0s: 7865, 0056, 0341, ..
Radix Sort • We loop through all the digits from right to left ( d iterations) • For each digit, we run counting sort O( n + k ) if k is the number of possible digits (10 if numbers are decimal) • O( d ( n + k ) )