Loading…
DAA · Sorting · Program 06 · In the record
Write a program in c to sort the elements using radix sort and find its execution time using the time function.
Algorithm: RadixSort(A, n) 1. Start 2. max <- largest element of A 3. exp <- 1 4. While (max/exp > 0) do 5. CountSort(A, n, exp) 6. exp <- exp*10 7. Print the sorted array A 8. Stop Algorithm: CountSort(A, n, exp) 1. For i <- 0 to 9 do 2. bucket[i] <- 0 3. For i <- 0 to (n-1) do 4. d <- (A[i]/exp) mod 10 5. bucket[d] <- bucket[d]+1 6. For i <- 1 to 9 do 7. bucket[i] <- bucket[i]+bucket[i-1] 8. For i <- (n-1) down to 0 do 9. d <- (A[i]/exp) mod 10 10. bucket[d] <- bucket[d]-1 11. output[bucket[d]] <- A[i] 12. For i <- 0 to (n-1) do 13. A[i] <- output[i] 14. Return
1#include<stdio.h>2#include<time.h>3 4int count=0;5 6void countSort(int a[],int n,int exp) {7 int output[n],bucket[10],i;8 9 for(i=0;i<10;i++)10 bucket[i]=0;11 for(i=0;i<n;i++) {12 count++;13 bucket[(a[i]/exp)%10]++;14 }15 for(i=1;i<10;i++)16 bucket[i]=bucket[i]+bucket[i-1];17 for(i=n-1;i>=0;i--) {18 count++;19 output[--bucket[(a[i]/exp)%10]]=a[i];20 }21 for(i=0;i<n;i++)22 a[i]=output[i];23}24 25int main() {26 int n,i,max,exp;27 printf("Enter the number of elements:");28 scanf("%d",&n);29 int a[n];30 printf("Enter the elements:");31 for(i=0;i<n;i++)32 scanf("%d",&a[i]);33 34 clock_t start=clock();35 max=a[0];36 for(i=1;i<n;i++)37 if(a[i]>max)38 max=a[i];39 for(exp=1;max/exp>0;exp=exp*10)40 countSort(a,n,exp);41 clock_t end=clock();42 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;43 44 printf("\nAfter radix sorting:");45 for(i=0;i<n;i++)46 printf("\t%d",a[i]);47 printf("\nNumber of operations:%d",count);48 printf("\nTime taken:%f seconds",time_taken);49 printf("\nTime complexity: O(d*n)");50 printf("\nSpace complexity: O(n+k)");51 printf("\n");52 return 0;53}6 ⏎ 42 8 27 14 35 19Enter the number of elements:6 Enter the elements:42 8 27 14 35 19 After radix sorting: 8 14 19 27 35 42 Number of operations:24 Time taken:0.000009 seconds Time complexity: O(d*n) Space complexity: O(n+k)
Run program 06 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.