Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. void ArrayClass<T>::mergeSort( int l, int r)
  2. { /* l is for left index and r is right index of the
  3. sub-array of arr to be sorted */
  4.  
  5. if (l < r)
  6. {
  7. // Same as (l+r)/2, but avoids overflow for
  8. // large l and h
  9. int m = l + (r - l) / 2;
  10. mergeSort(myarr, l, m); //first half
  11. mergeSort(myarr, (m + 1), r); // second half
  12.  
  13. mMerge(myarr, l, m, r);
  14. }
  15.  
  16. }
  17.  
  18. // Merges two subarrays of arr[].
  19. // First subarray is arr[l..m]
  20. // Second subarray is arr[m+1..r]
  21. template <class T>
  22. void ArrayClass<T>::mMerge(T arr[], int l, int m, int r)
  23. {
  24.  
  25. int n1 = m - l + 1;
  26. int n2 = r - m;
  27.  
  28. /* create temp arrays */
  29. T* L[n1], R[n2];
  30.  
  31. /* Copy data to temp arrays L[] and R[] */
  32. copyToArr(L[], arr[], 0, l, n1);
  33. copyToArr(R[], arr[], 0, j + 1, n2);
  34.  
  35. /* Merge the temp arrays back into arr[l..r]*/
  36. // Initial index of first subarray
  37. // Initial index of second subarray
  38. // Initial index of merged subarray
  39. arrayMerge(0, 0, 1, arr[], L[], R[], n1, n2);
  40.  
  41.  
  42. }
  43. template <class T>
  44. void ArrayClass<T>::copyToArr(T arr[],T myarr[], int index, int copyindex, int finish)
  45. {
  46. if (index < finish)
  47. {
  48. arr[index] = myarr[copyindex + index];
  49. dataToArr(arr, myarr, index + 1, copyindex, finish);
  50. }
  51. }
  52. template<class T>
  53. void ArrayClass<T>::arrayMerge(int index1,int index2,int index3,T mainarr[], T Leftarr[], T rightarr[],int end1,int end2)
  54. {
  55. if (index1 < end1 && index2 < end2)
  56. {
  57. if (Leftarr[index1] <= rightarr[index2])
  58. {
  59. mainarr[index3] = Leftarr[index1];
  60. index1++;
  61. }
  62. else
  63. {
  64. mainarr[index3] = rightarr[index2];
  65. index2++;
  66. }
  67. index3++;
  68. arrayMerge(index1, index2, index3, mainarr[], Leftarr[], rightarr[], end1, end2);
  69. }
  70. while (index1 < end1)
  71. {
  72. mainarr[index3] = Leftarr[index1];
  73. index1++;
  74. index3++;
  75. }
  76. while (index2 < end2)
  77. {
  78. mainarr[index3] = rightarr[index2];
  79. index2++;
  80. index3++;
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement