Advertisement
GAMELASTER

Untitled

Nov 13th, 2018
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. ```cpp
  2.  
  3. /* C program for Merge Sort */
  4. #include<stdlib.h>
  5. #include<stdio.h>
  6.  
  7. // Merges two subarrays of arr[].
  8. // First subarray is arr[l..m]
  9. // Second subarray is arr[m+1..r]
  10. void merge(int arr[], int l, int m, int r)
  11. {
  12. int i, j, k;
  13. int n1 = m - l + 1;
  14. int n2 = r - m;
  15.  
  16. /* create temp arrays */
  17. int L[n1], R[n2];
  18.  
  19. /* Copy data to temp arrays L[] and R[] */
  20. for (i = 0; i < n1; i++)
  21. L[i] = arr[l + i];
  22. for (j = 0; j < n2; j++)
  23. R[j] = arr[m + 1+ j];
  24.  
  25. /* Merge the temp arrays back into arr[l..r]*/
  26. i = 0; // Initial index of first subarray
  27. j = 0; // Initial index of second subarray
  28. k = l; // Initial index of merged subarray
  29. while (i < n1 && j < n2)
  30. {
  31. if (L[i] <= R[j])
  32. {
  33. arr[k] = L[i];
  34. i++;
  35. }
  36. else
  37. {
  38. arr[k] = R[j];
  39. j++;
  40. }
  41. k++;
  42. }
  43.  
  44. /* Copy the remaining elements of L[], if there
  45. are any */
  46. while (i < n1)
  47. {
  48. arr[k] = L[i];
  49. i++;
  50. k++;
  51. }
  52.  
  53. /* Copy the remaining elements of R[], if there
  54. are any */
  55. while (j < n2)
  56. {
  57. arr[k] = R[j];
  58. j++;
  59. k++;
  60. }
  61. }
  62.  
  63. /* l is for left index and r is right index of the
  64. sub-array of arr to be sorted */
  65. void mergeSort(int arr[], int l, int r)
  66. {
  67. if (l < r)
  68. {
  69. // Same as (l+r)/2, but avoids overflow for
  70. // large l and h
  71. int m = l+(r-l)/2;
  72.  
  73. // Sort first and second halves
  74. mergeSort(arr, l, m);
  75. mergeSort(arr, m+1, r);
  76.  
  77. merge(arr, l, m, r);
  78. }
  79. }
  80.  
  81. /* UTILITY FUNCTIONS */
  82. /* Function to print an array */
  83. void printArray(int A[], int size)
  84. {
  85. int i;
  86. for (i=0; i < size; i++)
  87. printf("%d ", A[i]);
  88. printf("\n");
  89. }
  90.  
  91. /* Driver program to test above functions */
  92. int main()
  93. {
  94. int arr[] = {12, 11, 13, 5, 6, 7};
  95. int arr_size = sizeof(arr)/sizeof(arr[0]);
  96.  
  97. printf("Given array is \n");
  98. printArray(arr, arr_size);
  99.  
  100. mergeSort(arr, 0, arr_size - 1);
  101.  
  102. printf("\nSorted array is \n");
  103. printArray(arr, arr_size);
  104. return 0;
  105. }
  106. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement