Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void ArrayClass<T>::mergeSort( int l, int r)
- { /* l is for left index and r is right index of the
- sub-array of arr to be sorted */
- if (l < r)
- {
- // Same as (l+r)/2, but avoids overflow for
- // large l and h
- int m = l + (r - l) / 2;
- mergeSort(myarr, l, m); //first half
- mergeSort(myarr, (m + 1), r); // second half
- mMerge(myarr, l, m, r);
- }
- }
- // Merges two subarrays of arr[].
- // First subarray is arr[l..m]
- // Second subarray is arr[m+1..r]
- template <class T>
- void ArrayClass<T>::mMerge(T arr[], int l, int m, int r)
- {
- int n1 = m - l + 1;
- int n2 = r - m;
- /* create temp arrays */
- T* L[n1], R[n2];
- /* Copy data to temp arrays L[] and R[] */
- copyToArr(L[], arr[], 0, l, n1);
- copyToArr(R[], arr[], 0, j + 1, n2);
- /* Merge the temp arrays back into arr[l..r]*/
- // Initial index of first subarray
- // Initial index of second subarray
- // Initial index of merged subarray
- arrayMerge(0, 0, 1, arr[], L[], R[], n1, n2);
- }
- template <class T>
- void ArrayClass<T>::copyToArr(T arr[],T myarr[], int index, int copyindex, int finish)
- {
- if (index < finish)
- {
- arr[index] = myarr[copyindex + index];
- dataToArr(arr, myarr, index + 1, copyindex, finish);
- }
- }
- template<class T>
- void ArrayClass<T>::arrayMerge(int index1,int index2,int index3,T mainarr[], T Leftarr[], T rightarr[],int end1,int end2)
- {
- if (index1 < end1 && index2 < end2)
- {
- if (Leftarr[index1] <= rightarr[index2])
- {
- mainarr[index3] = Leftarr[index1];
- index1++;
- }
- else
- {
- mainarr[index3] = rightarr[index2];
- index2++;
- }
- index3++;
- arrayMerge(index1, index2, index3, mainarr[], Leftarr[], rightarr[], end1, end2);
- }
- while (index1 < end1)
- {
- mainarr[index3] = Leftarr[index1];
- index1++;
- index3++;
- }
- while (index2 < end2)
- {
- mainarr[index3] = rightarr[index2];
- index2++;
- index3++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement