Advertisement
shawonrog

mergesort mizan version

Jun 23rd, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1.  
  2. #include<stdlib.h>
  3. #include<stdio.h>
  4.  
  5.  
  6. void merge(int arr[], int l, int m, int r)
  7. {
  8. int i, j, k;
  9. int n1 = m - l + 1;
  10. int n2 = r - m;
  11.  
  12.  
  13. int L[n1], R[n2];
  14.  
  15.  
  16. for (i = 0; i < n1; i++)
  17. L[i] = arr[l + i];
  18. for (j = 0; j < n2; j++)
  19. R[j] = arr[m + 1+ j];
  20.  
  21.  
  22. i = 0;
  23. j = 0;
  24. k = l;
  25. while (i < n1 && j < n2)
  26. {
  27. if (L[i] <= R[j])
  28. {
  29. arr[k] = L[i];
  30. i++;
  31. }
  32. else
  33. {
  34. arr[k] = R[j];
  35. j++;
  36. }
  37. k++;
  38. }
  39.  
  40.  
  41. while (i < n1)
  42. {
  43. arr[k] = L[i];
  44. i++;
  45. k++;
  46. }
  47.  
  48.  
  49. while (j < n2)
  50. {
  51. arr[k] = R[j];
  52. j++;
  53. k++;
  54. }
  55. }
  56.  
  57.  
  58. void mergeSort(int arr[], int l, int r)
  59. {
  60. if (l < r)
  61. {
  62.  
  63. int m = l+(r-l)/2;
  64.  
  65. mergeSort(arr, l, m);
  66. mergeSort(arr, m+1, r);
  67.  
  68. merge(arr, l, m, r);
  69. }
  70. }
  71.  
  72.  
  73. void printArray(int A[], int size)
  74. {
  75. int i;
  76. for (i=0; i < size; i++)
  77. printf("%d ", A[i]);
  78. printf("\n");
  79. }
  80.  
  81.  
  82. int main()
  83. {
  84. int arr[] = {12, 11, 13, 5, 6, 7};
  85. int arr_size = sizeof(arr)/sizeof(arr[0]);
  86.  
  87. printf("Given array is \n");
  88. printArray(arr, arr_size);
  89.  
  90. mergeSort(arr, 0, arr_size - 1);
  91.  
  92. printf("\nSorted array is \n");
  93. printArray(arr, arr_size);
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement