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


After sorting:


Number of basic operations = 0