// This version of the merge sort is adapted from Sedgewick's "Algorithms," p. 166: void mergeSort(int iArrayA[], int iArrayB[], int l, int r) { int i = 0; // l is the left index of the array int j = 0; // r is the right index of the array int k = 0; // i, j, and k are loop indices. int m = 0; // m is the middle of the array index. int iMinI = 0; // For minimal index. int iMaxJ = 0; // For maximal index. if (r - l > 0) // Recursion stop condition. { m = (r + l) / 2; // Integer division to find the middle. mergeSort(iArrayA, iArrayB, l, m); // Branching recursion, mergeSort(iArrayA, iArrayB, m + 1, r); // splitting the array (pushed onto runtime stack). // Merge the two arrays (popped from runtime stack): iMinI = m; for (i = m; i >= l; i--) // Copy left of A to left of B. { iArrayB[i] = iArrayA[i]; iMinI = i; // Set the min index. } iMaxJ = m + l; for (j = m + 1; j <= r; j++) // Copy right of A to right of B in reverse: { iArrayB[r + m + 1 - j] = iArrayA[j]; iMaxJ = j; // Set the max index. } for (k = l; k <= r; k++) // Do the merging. { if (iArrayB[iMinI] < iArrayB[iMaxJ]) { iArrayA[k] = iArrayB[iMinI]; iMinI++; } else { iArrayA[k] = iArrayB[iMaxJ]; iMaxJ--; } } } }