/*
* A is an array and p, q, and r are indices numbering elements of the array
* such that p <= q < r.
*
* This procedure assumes that the subarrays A[p. .q] and A[q + 1. .r] are in
* sorted order. It merges them to form a single sorted subarray that replaces
* the current subarray A[p. .r].
*/
void merge(int A[], int p, int q, int r) {
int i, j, k, size;
int* B;
size = r - p + 1;
B = new int[size]; /* temp arry for storing the merge result */
/* initialize B */
for (i = 0; i < size; ++i) {
B[i] = 0;
}
i = p;
j = q + 1;
k = 0;
/* compare and copy the smaller to B */
while (i <= q && j <= r) {
if (A[i] < A[j]) {
B[k++] = A[i++];
} else {
B[k++] = A[j++];
}
}
/* copy the rest to B */
while (i <= q) {
B[k++] = A[i++];
}
while (j <= r) {
B[k++] = A[j++];
}
/* replace A[p..r] with B[0..r-p] */
for (i = p, k = 0; i <= r; ++i, ++k) {
A[i] = B[k];
}
delete[] B;
}
/*
* This procedure sorts the elements in the subarray A[p. .r].
*
* If p >= r, the subarray has at most one element and is therefore
* already sorted. Otherwise, the divide step simply computes an index
* q that partitions A[p. .r] into two subarrays: A[p. .q], containing n/2
* elements, and A[q + 1. .r], containing n/2 elements.
*/
void mergeSort(int A[], int p, int r) {
if (p >= r) return;
int q = (p + r) / 2;
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
merge(A, p, q, r);
}
* A is an array and p, q, and r are indices numbering elements of the array
* such that p <= q < r.
*
* This procedure assumes that the subarrays A[p. .q] and A[q + 1. .r] are in
* sorted order. It merges them to form a single sorted subarray that replaces
* the current subarray A[p. .r].
*/
void merge(int A[], int p, int q, int r) {
int i, j, k, size;
int* B;
size = r - p + 1;
B = new int[size]; /* temp arry for storing the merge result */
/* initialize B */
for (i = 0; i < size; ++i) {
B[i] = 0;
}
i = p;
j = q + 1;
k = 0;
/* compare and copy the smaller to B */
while (i <= q && j <= r) {
if (A[i] < A[j]) {
B[k++] = A[i++];
} else {
B[k++] = A[j++];
}
}
/* copy the rest to B */
while (i <= q) {
B[k++] = A[i++];
}
while (j <= r) {
B[k++] = A[j++];
}
/* replace A[p..r] with B[0..r-p] */
for (i = p, k = 0; i <= r; ++i, ++k) {
A[i] = B[k];
}
delete[] B;
}
/*
* This procedure sorts the elements in the subarray A[p. .r].
*
* If p >= r, the subarray has at most one element and is therefore
* already sorted. Otherwise, the divide step simply computes an index
* q that partitions A[p. .r] into two subarrays: A[p. .q], containing n/2
* elements, and A[q + 1. .r], containing n/2 elements.
*/
void mergeSort(int A[], int p, int r) {
if (p >= r) return;
int q = (p + r) / 2;
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
merge(A, p, q, r);
}