fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int count = 0;
  6.  
  7. void merge(int a[], int low, int mid, int high)
  8. {
  9. int i = low, j = mid + 1, k = 0;
  10. int c[10000];
  11.  
  12. while (i <= mid && j <= high) {
  13. count++; // Count each comparison
  14. if (a[i] < a[j])
  15. c[k++] = a[i++];
  16. else
  17. c[k++] = a[j++];
  18. }
  19.  
  20. while (i <= mid)
  21. c[k++] = a[i++];
  22. while (j <= high)
  23. c[k++] = a[j++];
  24.  
  25. for (i = low, j = 0; j < k; i++, j++)
  26. a[i] = c[j];
  27. }
  28.  
  29. void merge_sort(int a[], int low, int high) {
  30. if (low < high) {
  31. int mid = (low + high) / 2;
  32. merge_sort(a, low, mid);
  33. merge_sort(a, mid + 1, high);
  34. merge(a, low, mid, high);
  35. }
  36. }
  37.  
  38. int main() {
  39. int a[10000], n, i;
  40.  
  41. printf("Enter the number of elements in the array: ");
  42. scanf("%d", &n);
  43.  
  44. printf("All the elements:\n");
  45. srand(time(0));
  46. for (i = 0; i < n; i++) {
  47. a[i] = rand();
  48. printf("%d ", a[i]);
  49. }
  50.  
  51. merge_sort(a, 0, n - 1);
  52.  
  53. printf("\n\nAfter sorting:\n");
  54. for (i = 0; i < n; i++)
  55. printf("%d ", a[i]);
  56.  
  57. printf("\n\nNumber of basic operations = %d\n", count);
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 5320KB
stdin
3
56484 23563 35632
stdout
Enter the number of elements in the array: All the elements:
121620641 168957646 517972272 

After sorting:
121620641 168957646 517972272 

Number of basic operations = 3