I can't figure out what is wrong with my MergeSort
function. This is my code:
void Merge(int* A, int p, int q, int r)
{
int B[100], i = 0, j = 0, k = 0;
i = p;
k = p;
j = q + 1;
while (i <= q && j <= r)
{
if (A[i] <= A[j])
{
B[k] = A[i];
k++;
i++;
}
else
{
B[k] = A[j];
k++;
j++;
}
}
while (i <= q)
{
B[k] = A[i];
k++;
i++;
}
while (j <= r)
{
B[k] = A[j];
k++;
j++;
}
for (i = p; i < r; i++)
{
A[i] = B[i];
}
}
void MergeSort(int A[], int p, int r)
{
int q;
if (p < r)
{
q = (p + r) / 2;
MergeSort(A, p, q);
MergeSort(A, q + 1, r);
Merge(A, p, q, r);
}
}
int main(void)
{
int N[10];
N[0] = 4;
N[1] = 5;
N[2] = 8;
N[3] = 12;
N[4] = 7;
N[5] = 3;
N[6] = 23;
N[7] = 1;
N[8] = 90;
N[9] = 26;
MergeSort(N, 0, 9);
for (int i = 0; i < 10; i++)
{
cout << N[i] << endl;
}
}
The output of program is: 1, 3, 1, 4, 5, 7, 7, 7, 26, 26, which is obviously wrong. However I just don't see what is wrong in code, to me everthing looks good. I googled some C++ codes of MargeSort
and try to debug it but i can't find mistake. Anyone see it?