/** ********************* * Merge sort. Results are stored in the member variable data. ********************* */ publicvoidmergeSort() { // Step 1. Allocate space.
int tempRow; // The current row int tempGroups; // Number of groups int tempActualRow; // Only 0 or 1 inttempNextRow=0; int tempGroupNumber; int tempFirstStart, tempSecondStart, tempSecondEnd; int tempFirstIndex, tempSecondIndex; int tempNumCopied; for (inti=0; i < length; i++) { System.out.print(data[i]); } // Of for i System.out.println();
DataNode[][] tempMatrix = newDataNode[2][length];
// Step 2. Copy data. for (inti=0; i < length; i++) { tempMatrix[0][i] = data[i]; } // Of for i
// Step 3. Merge. log n rounds tempRow = -1; for (inttempSize=1; tempSize <= length; tempSize *= 2) { // Reuse the space of the two rows. tempRow++; System.out.println("Current row = " + tempRow); tempActualRow = tempRow % 2; tempNextRow = (tempRow + 1) % 2;
tempMatrix[tempNextRow][tempFirstStart + tempNumCopied] = tempMatrix[tempActualRow][tempFirstIndex]; tempFirstIndex++; System.out.println("copying " + tempMatrix[tempActualRow][tempFirstIndex]); } else { tempMatrix[tempNextRow][tempFirstStart + tempNumCopied] = tempMatrix[tempActualRow][tempSecondIndex]; System.out.println("copying " + tempMatrix[tempActualRow][tempSecondIndex]); tempSecondIndex++; } // Of if tempNumCopied++; } // Of while
while (tempFirstIndex <= tempSecondStart - 1) { tempMatrix[tempNextRow][tempFirstStart + tempNumCopied] = tempMatrix[tempActualRow][tempFirstIndex]; tempFirstIndex++; tempNumCopied++; } // Of while
while (tempSecondIndex <= tempSecondEnd) { tempMatrix[tempNextRow][tempFirstStart + tempNumCopied] = tempMatrix[tempActualRow][tempSecondIndex]; tempSecondIndex++; tempNumCopied++; } // Of while } // Of for groupNumber
System.out.println("Round " + tempRow); for (inti=0; i < length; i++) { System.out.print(tempMatrix[tempNextRow][i] + " "); } // Of for j System.out.println(); } // Of for tempStepSize