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