Reputation: 717
#include "stdafx.h"
#include <iostream>
using namespace std;
using namespace System;
void mergesort(int a[], int p, int r);
void merge(int a[], int p, int q, int r);
int main(array<System::String ^> ^args)
{
int result[2] = { 1, 0 };
int *p;
p = result;
mergesort(p, 0,1);
while (1);
return 0;
}
void mergesort(int a[],int p, int r)
{
if (p < r)
{
int q = (p + r) / 2;
mergesort(a, p, q);
cout << endl;
mergesort(a, q + 1, r);
cout << endl;
merge(a,p,q,r);
for (int i = 0; i < 2; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
}
void merge(int a[], int p, int q, int r)
{
int left[100] = {};
int right[100] = {};
for (int i = 0; i < (q - p + 1); i++)
{
left[i] = *(a + p + i);
left[i + 1] = 999;
}
for (int i = 0; i < (r - q); i++)
{
right[i] = *(a + q + 1 + i);
right[i + 1] = 999;
}
for (int k = p; k < r+1; k++)
{
int i = 0;
int j = 0;
if (left[i] <= right[j])
{
a[k] = left[i++];
}
else
{
a[k] = right[j++]; **// it always goes into this route? why does not left[i]<=right[j] work?**
}
}
}
Here is my code about a basic merge sort. I cannot enter the first IF statement in the merge function. Why does if (left[i] <= right[j])
not work? I have tried may time whatever the left[i]
is. The program just goes to the else statement.
Upvotes: 0
Views: 120
Reputation: 163
If your intent is to use variables i and j in the loop only then try to restrict the scope of i and j to the loop by doing following.
for (int k = p, i = 0, j = 0; k < r+1; k++)
{
if (left[i] <= right[j])
{
a[k] = left[i++];
}
else
{
a[k] = right[j++];
}
}
Upvotes: 0
Reputation: 43477
for (int k = p; k < r+1; k++)
{
int i = 0;
int j = 0;
if (left[i] <= right[j])
{
a[k] = left[i++];
}
else
{
a[k] = right[j++]; **// it always goes into this route? why does not left[i]<=right[j] work?**
}
}
This does not do what you think it does. It will always compare left[0]
with right[0]
, because you declare i
and j
inside the for
loop, so they will be reset to 0 on each iteration.
To make them retain their values, declare them outside the loop:
int i = 0;
int j = 0;
for (int k = p; k < r+1; k++)
{
if (left[i] <= right[j])
{
a[k] = left[i++];
}
else
{
a[k] = right[j++]; **// it always goes into this route? why does not left[i]<=right[j] work?**
}
}
Upvotes: 4