V
voger
Hi everyone
Can anyone please explain this strange behavior?
I have this function that is supposed to copy the contents of one array to
one other array, but sorted. I don't know if the logic is correct but when
I try to debug this the do/while loop results in an endless loop. The Two
first values of the unsorted array are
unsorted[0] = 8
unsorted[1] = 9
I tried to step over it with a debugger. When it reaches to the do/while
loop it checks the if statement which results to false, checks the else if
statement which results to true, sets larger to true, DOESN'T check the
while statement at all and goes back to the if statement. Where is the
mistake?
void sort(int sorted[], int unsorted[])
{
bool larger = false;
//first number is just copied
sorted[0] = unsorted[0];
// start sorting
for(int i = 1; i<10; i++)
{
// first copy the value to the sorted array
sorted = unsorted;
// then start comparing
int j = i;
do
{
// if less than previous then swap
if(sorted[j] < sorted[j -1])
{
int temp = sorted[j -1];
sorted[j -1] = sorted[j];
sorted[j] = temp;
j--;
larger = false;
}
// else do nothing
else if(sorted[j] >= sorted[j -1])
{
larger = true;
}
}while(j != 0 || !larger);
}
}
Can anyone please explain this strange behavior?
I have this function that is supposed to copy the contents of one array to
one other array, but sorted. I don't know if the logic is correct but when
I try to debug this the do/while loop results in an endless loop. The Two
first values of the unsorted array are
unsorted[0] = 8
unsorted[1] = 9
I tried to step over it with a debugger. When it reaches to the do/while
loop it checks the if statement which results to false, checks the else if
statement which results to true, sets larger to true, DOESN'T check the
while statement at all and goes back to the if statement. Where is the
mistake?
void sort(int sorted[], int unsorted[])
{
bool larger = false;
//first number is just copied
sorted[0] = unsorted[0];
// start sorting
for(int i = 1; i<10; i++)
{
// first copy the value to the sorted array
sorted = unsorted;
// then start comparing
int j = i;
do
{
// if less than previous then swap
if(sorted[j] < sorted[j -1])
{
int temp = sorted[j -1];
sorted[j -1] = sorted[j];
sorted[j] = temp;
j--;
larger = false;
}
// else do nothing
else if(sorted[j] >= sorted[j -1])
{
larger = true;
}
}while(j != 0 || !larger);
}
}