// File: mergesort.cpp // Merge Sort Routines #ifndef MERGESORT_CPP #define MERGESORT_CPP #include #include using namespace std ; template void merge( T A[], int low1, int high1, int low2, int high2 ) { int t=0, i1=low1, i2=low2 ; // Sanity check assert(low2 == high1 + 1) ; // Allocate space for temporary array // T *temp = new T[high2 - low1 + 1] ; // while there are elements in both halves, copy the lowest one // while (i1 <= high1 && i2 <= high2) { if (A[i1] < A[i2]) { temp[t++] = A[i1++] ; } else { temp[t++] = A[i2++] ; } } // copy any remaining elements, if any // while (i1 <= high1) { temp[t++] = A[i1++] ; } while (i2 <= high2) { temp[t++] = A[i2++] ; } // copy the now-sorted elements back into the original array // for (t = low1; t <= high2; t++) { A[t] = temp[t - low1] ; } delete [] temp ; } template void MergeSort(T A[], int low, int high) { // cout << "MergeSort: low = " << low << ", high = " << high << endl ; if (low >= high) return ; int mid = (low + high)/2 ; MergeSort(A, low, mid) ; MergeSort(A, mid + 1, high) ; merge(A, low, mid, mid + 1, high) ; } #endif