// Mergesort elements of the array A between left and right inclusive void mergesort (int [] A, int left, int right) { if (left < right) { // recurse only if 2 or more elements int center = (left + right) / 2; mergesort (A, left, center); mergesort (A, center + 1, right); merge (A, left, center + 1, right); } } // Merge the sorted subarray A[leftPos, ..., rightPos - 1] and // the sorted subarray A[rightPos, ..., rightEnd] into a temp // array B. Then copy B[0, ...] into A[leftPos ... rightEnd] int merge (int [] A, int leftPos, int rightPos, int rightEnd) { int leftEnd = rightPos - 1; // assumes rightPos > leftPos int numElements = rightEnd - leftPos + 1; int [] B = new int [numElements]; int bPos = 0; // While *both* left and right have elements remaining, compare smallest of each. while (leftPos <= leftEnd && rightPos <= rightEnd) { // If left element smaller, copy it, and adjust ptrs if (A[leftPos] <= A[rightPos]) B[bPos++] = A[leftPos++]; // Else copy right element and adjust else B[bPos++] = A[rightPos++]; } // Exactly one of left and right now have elements remaining. // Copy from whichever one is non-empty. // Only one of the two loops below will execute. while (leftPos <= leftEnd) B[bPos++] = A[leftPos++]; while (rightPos <= rightEnd) B[bPos++] = A[rightPos++]; // B contains the merged results. Copy them back to A. leftPos = rightEnd - numElements + 1; for (bPos = 0; bPos < numElements; bPos ++) A[leftPos++] = B[bPos]; } }