fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. int count=0;
  5. void merge(int a[], int low,int mid,int high)
  6. {
  7. int i,j,k,c[10000];
  8. i=low, j=mid+1, k=0;
  9. while((i<=mid) && (j<=high))
  10. {
  11. count++;
  12. //choose the least element and store in Temporary array 'C'
  13. if(a[i]<a[j])
  14. c[k++]=a[i++];
  15. else
  16. c[k++]=a[j++];
  17. }
  18. //Copy the remaining array elements from any one of sub-array
  19. while(i<=mid)
  20. c[k++]=a[i++];
  21. while(j<=high)
  22. c[k++]=a[j++];
  23. for(i=low,j=0;j<k;i++, j++)
  24. a[i]=c[j];
  25. }
  26. void merge_sort(int a[], int low, int high)
  27. {
  28. int mid;
  29. if(low < high)
  30. {
  31. //Divide the given array into 2 parts
  32. mid=(low+high)/2;
  33. merge_sort(a,low,mid);
  34. merge_sort(a,mid+1,high);
  35. merge(a,low,mid,high);
  36. }
  37. }
  38. int main()
  39.  
  40. {
  41. int a[10000],n,i;
  42. printf("Enter the number of elements in an array:");
  43. scanf("%d",&n);
  44. printf("All the elements:");
  45. srand(time(0));
  46. for(i=0;i<n;i++)
  47. {
  48. a[i]=rand();
  49. printf("%d ",a[i]);
  50. }
  51. merge_sort(a,0,n-1);
  52. printf("\nAfter sorting\n");
  53. for(i=0;i<n;i++)
  54. printf("%d ", a[i]);
  55. printf("\nNumber of basic operations = %d\n",count);
  56. }
Success #stdin #stdout 0s 5328KB
stdin
5
24759 329 8704 24132 7473
stdout
Enter the number of elements in an array:All the elements:788790918 1773073834 1235347633 871029030 1532714125 
After sorting
788790918 871029030 1235347633 1532714125 1773073834 
Number of basic operations = 8