I have an array as such:
int array[] = { 1,3,2,5,4,7,6,9,8,10 };
When I try to step through the array and compare the numbers none of them trigger the if condition thereby triggering the swap:
for( int i=0; i<9; i++)
{
if (array[i] > array[i++])
{
cout << "Swapping" << array[i] << " " << array[i++]<< endl;
int temp = 0;
temp = array[i];
array[i] = array[i++];
array[i++] = temp;
temp = 0;
}
}
Is there some detail of comparing integers that I am missing? Are they treated differently because they are in an array?
i++
means "return i
and set i = i + 1
". So each time you're using i++
you are increasing i
by one which ruins the loop. use i+1
instead.
i++
is a post-increment, and returns the previous value.
if (array[i] > array[i+1])
Right now, you're comparing array[i]
with itself.
You also need the following:
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
You're incrementing your i too many times. Change your if statement to:
if ( array[i] > array[ i + 1 ] )
and fix all the other increments likewise apart from the one in your for loop.
The expressions:
array[i] < array[i++]
and
array[i] = array[i++]
is undefined behavior, so anything can happen. (As others have pointed out, it's probably not what you want anyway. As written, you're incrementing i
5 times each time you go through the loop.)
You should use the following code:-
for( int i=0; i<9; i++)
{
if (array[i] > array[i+1])
{
cout << "Swapping" << array[i] << " " << array[i+1]<< endl;
int temp = 0;
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
temp = 0;
}
}
The statement: if (array[i] > array[i++])
is equivalent to if (array[i] > array[i])
which doesn't make sense.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.