fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. void merge(int a[],int l,int m,int r){
  5. int n1=m-l+1,n2=r-m,i,j,k;
  6. int *L=(int*)malloc(n1*sizeof(int));
  7. int *R=(int*)malloc(n2*sizeof(int));
  8. for(i=0;i<n1;i++)
  9. L[i]=a[l+i];
  10. for(j=0;j<n2;j++)
  11. R[j]=a[m+1+j];
  12. i=0;
  13. j=0;
  14. k=l;
  15. while(i<n1&&j<n2)
  16. a[k++]=(L[i]<=R[j])?L[i++]:R[j++];
  17. while(i<n1)
  18. a[k++]=L[i++];
  19. while(j<n2)
  20. a[k++]=R[j++];
  21. free(L);
  22. free(R);
  23. }
  24. void sort(int a[],int l,int r){
  25. if(l<r){
  26. int m=(l+r)/2;
  27. sort(a,l,m);
  28. sort(a,m+1,r);
  29. merge(a,l,m,r);
  30. }
  31. }
  32. int main(){
  33. int n,i;
  34. printf("Enter the number of elements:");
  35. scanf("%d",&n);
  36. if(n<=5000){
  37. printf("Please enter a value greater than 5000");
  38. return 0;
  39. }
  40. int *a=(int*)malloc(n*sizeof(int));
  41. srand(time(NULL));
  42. for(i=0;i<n;i++)
  43. a[i]=rand()%100000;
  44. clock_t s=clock();
  45. for(i=0;i<1000;i++)
  46. sort(a,0,n-1);
  47. clock_t e=clock();
  48. printf("Time taken to sort %d elements: %f seconds\n",n,((double)(e-s))/CLOCKS_PER_SEC/1000);
  49. free(a);
  50. return 0;
  51. }
Success #stdin #stdout 1.27s 5320KB
stdin
Standard input is empty
stdout
Enter the number of elements:Time taken to sort 22004 elements: 0.001268 seconds