To perform radix sort on the array [170, 45, 75, 90, 802, 24, 2, 66], we follow these steps:
How does Radix Sort Algorithm work | Step 1Step 1: Find the largest element in the array, which is 802. It has three digits, so we will iterate three times, once for each significant place.
Step 2: Sort the elements based on the unit place digits (X=0). We use a stable sorting technique, such as counting sort, to sort the digits at each significant place. It's important to understand that the default implementation of counting sort is unstable i.e. same keys can be in a different order than the input array. To solve this problem, We can iterate the input array in reverse order to build the output array. This strategy helps us to keep the same keys in the same order as they appear in the input array.
Sorting based on the unit place:
- Perform counting sort on the array based on the unit place digits.
- The sorted array based on the unit place is [170, 90, 802, 2, 24, 45, 75, 66].
How does Radix Sort Algorithm work | Step 2Step 3: Sort the elements based on the tens place digits.
Sorting based on the tens place:
- Perform counting sort on the array based on the tens place digits.
- The sorted array based on the tens place is [802, 2, 24, 45, 66, 170, 75, 90].
How does Radix Sort Algorithm work | Step 3Step 4: Sort the elements based on the hundreds place digits.
Sorting based on the hundreds place:
- Perform counting sort on the array based on the hundreds place digits.
- The sorted array based on the hundreds place is [2, 24, 45, 66, 75, 90, 170, 802].
How does Radix Sort Algorithm work | Step 4Step 5: The array is now sorted in ascending order.
The final sorted array using radix sort is [2, 24, 45, 66, 75, 90, 170, 802].
How does Radix Sort Algorithm work | Step 5