Foundations of Data Structures Practical Session #12 Linear Sorting
Sorting algorithms criteria 2
Comparison sorting 3
Linear sorting numeric Linear sorting is the problem of sorting a collection of items with numeric keys. The ability to perform arithmetic operations on the keys allows faster algorithms than comparison-based algorithms in many cases. Classical examples include: Counting sort Radix sort Bucket sort 4
Counting sort 5
Counting sort cont’d Counting-Sort (A, B, k) for i ← 1 to k C[i] ← 0 // Calc histogram for j ← 1 to n C[A[j]] ← C[A[j]] + 1 // Calc start index (backwards) in output for each key for i ← 2 to k C[i] ← C[i] + C[i-1] // Copy to output array for j ← n downto 1 B[C[A[j]]] ← A[j] C[A[j]] ← C[A[j]] – 1 return B Example A: C: B: C:0 0 0
Counting sort analysis 7
Radix sort 8
Radix sort analysis For example, sort 7 numbers with 3 digits in decimal base Sorted by 1 st digit Sorted by 2 nd (and 1 st ) digit Sorted! Input array
Radix sort cont’d 10
Bucket sort 11
Bucket sort cont’d Example 12 A: B: A:
Bucket sort analysis 13
Sort algorithms review Stable In Place Extra Space Running time KeysType Worst case Average √√O(1)O(n 2 )any Insertion sort √XO(n)O(nlogn)any Merge sort X√O(1)O(nlogn)any Heap sort X√O(1)O(n 2 )O(nlogn)anyQuicksort √XO(n+k) integers [1..k] Counting sort √ Depends on the stable sort used O(d(b+n)) d digits in base b Radix sort √XO(n)O(n 2 )O(n)[0,1) Bucket sort 14
Question 1 15
Question 1 solution 16
Question 2 17
Question 2 solution 18
Question 2 solution cont’d 19
Question 2 solution cont’d 20
Question 3 21
Question 3 solution 22
Question 4 23
Question 4 solution 24
Question 4 solution cont’d 25