void Functions::topDownSplitMerge(RefArrayXd array1, RefArrayXd arrayCopy1, RefArrayXd array2, RefArrayXd arrayCopy2, int beginIndex, int endIndex) { // If input array1 contains only 1 element it is already sorted if (endIndex - beginIndex < 2) return; // Find mid-point of the input array int middleIndex = (endIndex + beginIndex) / 2; // Separate first-half and second-half of the array and repeat the process topDownSplitMerge(array1, arrayCopy1, array2, arrayCopy2, beginIndex, middleIndex); topDownSplitMerge(array1, arrayCopy1, array2, arrayCopy2, middleIndex, endIndex); // Order elements in each half and merge them into a single, sorted, array topDownMerge(array1, arrayCopy1, array2, arrayCopy2, beginIndex, middleIndex, endIndex); // Copy elements of array sorted into original array int length = endIndex - beginIndex; array1.segment(beginIndex, length) = arrayCopy1.segment(beginIndex, length); array2.segment(beginIndex, length) = arrayCopy2.segment(beginIndex, length); }
void CMergeSort::topDownSplitMerge(std::vector<double> * inputA, int iBegin, int iEnd, std::vector<double> * outputB) { int iMiddle; // for separating the array into two smaller array if (iEnd - iBegin < 2) // the array has maximum 1 number return; iMiddle = (iEnd + iBegin) / 2; topDownSplitMerge(inputA, iBegin, iMiddle, outputB); // left half topDownSplitMerge(inputA, iMiddle, iEnd, outputB); // right half topDownMerge(inputA, iBegin, iMiddle, iEnd, outputB); // merge two halves copyArray(inputA, iBegin, iEnd, outputB); }
void Functions::topDownMergeSort(RefArrayXd array1, RefArrayXd array2) { assert(array1.size() == array2.size()); ArrayXd arrayCopy1 = array1; ArrayXd arrayCopy2 = array2; topDownSplitMerge(array1, arrayCopy1, array2, arrayCopy2, 0, arrayCopy1.size()); }
std::vector<double> CMergeSort::run(std::vector<double> inputA) { std::vector<double>* outputB= new std::vector<double>(inputA); topDownSplitMerge(&inputA, 0, inputA.size(), outputB); return inputA; }