Expt-16 - Implementation of Radix Sort
Expt-16 - Implementation of Radix Sort
Expt-16 - Implementation of Radix Sort
countingSort(array, d)
max <- find largest element among dth place elements
initialize count array with all zeros
for j <- 0 to size
find the total count of each unique digit in dth place of elements and
store the count at jth index in count array
for i <- 1 to max
find the cumulative sum and store it in count array itself
for j <- size down to 1
restore the elements to array
decrease count of each element restored by 1
Explanation:
Find the largest element in the array, i.e. max. Let X be the number of digits in max.
X is calculated because we have to go through all the significant places of all
elements.
In this array [121, 432, 564, 23, 1, 45, 788], we have the largest number 788. It has 3
digits. Therefore, the loop should go up to hundreds place (3 times).
Now, go through each significant place one by one.
Use any stable sorting technique to sort the digits at each significant place. We
have used counting sort for this.
Example:
Program Code:
for(int i=0;i<10;i++)
count[i]=0;
for(int i=0;i<n;i++)
count[(a[i]/div)%10]++;
for(int i=1;i<10;i++)
count[i]+=count[i-1];
for(int i=n-1;i>-1;i--){
temp[count[(a[i]/div)%10]-1]=a[i];
count[(a[i]/div)%10]--;
}
for(int i=0;i<n;i++)
a[i]=temp[i];
int max=0;
for(int i=0;i<n;i++)
if(a[i]>max)
max=a[i];
for(int div=1;max/div>0;div*=10){
countingSort(a,n,div);
}
}
static void printArr(int a[], int n)
{
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
int a[]={90,69,17,29,16,10};
int n = a.length;
System.out.print("Before sorting array elements are - \n");
printArr(a, n);
System.out.print("\nAfter sorting array elements are - \n");
radixSort(a,a.length);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
Output Screenshots:
correct input
RESULT: Implementation of Radix Sort Thus, the programs for the given problem statements has been
executed and the results are verified successfully.