#include using namespace std; // merge function prototype template void merge(Type* array, Type* tempArray, int low, int middle, int high); // merge sort helper prototype template void mergeSortHelper(Type* array, Type* tempArray, int low, int high); // merge sort prototype template void mergeSort(Type* array, int size); template void merge(Type* array, Type* tempArray, int low, int middle, int high) { int i, j, k; for (i = low; i <= high; i++) { // copy into temp array tempArray[i] = array[i]; } i = low; //indices into subarrays j = middle+1; k = low; //indices into output array while ((i <= middle) && (j <= high)) { if (tempArray[i] <= tempArray[j]) // if lhs item is smaller array[k++] = tempArray[i++]; // put in final array, increment else // final array position, lhs index array[k++] = tempArray[j++]; // else put rhs item in final array } // increment final array position // rhs index // at this point, one of the two arrays has been consumed while (i <= middle) array[k++] = tempArray[i++]; // copy the rest of the data } // only need to copy if in lhs // rhs array already in right place template void mergeSortHelper(Type* array, Type* tempArray, int low, int high) { if (low < high) { int middle = (low + high) / 2; mergeSortHelper(array, tempArray, low, middle); mergeSortHelper(array, tempArray, middle+1, high); merge(array, tempArray, low, middle, high); } } template void mergeSort(Type* array, int size) { Type* tempArray = new Type[size]; mergeSortHelper(array, tempArray, 0, size-1); delete [] tempArray; } int main(int argc, char* argv[]) { int i; int size = 5; int* data = new int[5]; data[0] = 9; data[1] = 8; data[2] = 7; data[3] = 6; data[4] = 5; cout << "Unsorted data: " << endl; for (i = 0; i < size; i++) { cout << data[i] << endl; } mergeSort(data,size); cout << "Sorted data: " << endl; for (i = 0; i < size; i++) { cout << data[i] << endl; } double* data2 = new double[5]; data2[0] = 9.2; data2[1] = 8.5; data2[2] = 8.4; data2[3] = 6.2; data2[4] = 5.1; cout << "Unsorted data: " << endl; for (i = 0; i < size; i++) { cout << data2[i] << endl; } mergeSort(data2,size); cout << "Sorted data: " << endl; for (i = 0; i < size; i++) { cout << data2[i] << endl; } }