 # confusing for-que

can someone please explain the following code. I don't understand what happens aofter the "if". And what are the print commands per iteration level?
Thanks!
x = c( 3 3 , 55 , 22 , 44 , 11 )
for ( i in 1 : ( length ( x ) −1 ) ) {
for ( j in 1 : ( length ( x ) −1 ) ) {
if ( x [ j ] > x [ j + 1] ) {
tmp=x[ j ]
x [ j ] = x [ j +1]
x [ j +1] = tmp
}
}

print ( i )
print ( x )
}

``````x = c( 3 3 , 55 , 22 , 44 , 11 )
for ( i in 1 : ( length ( x ) −1 ) ) {
for ( j in 1 : ( length ( x ) −1 ) ) {
if ( x [ j ] > x [ j + 1] ) {
tmp=x[ j ]
x [ j ] = x [ j +1]
x [ j +1] = tmp
}
}

print ( i )
print ( x )
}
``````

The code starts by defining x as a numeric vector with five elements and then moves to two nested for loops that each iterate from 1 to 4 (because length(x) - 1 = 4). Let's see what happens on the first pass through the j loop when both i and j are 1. The if tests `x > x[1+1]` which is `x > x` or `33 > 55`. That is FALSE, so the code within the if is not executed and there is no other code in the j loop, so the loop runs the next iteration with j = 2. The if tests `x > x[2+1]` which is `x > x` or `55 > 22`. That is TRUE and the code within the if gets executed. The value of x[j], which is x and equals 55, gets stored in tmp. Then the value of x[j+1], which is x and equals 22, gets stored in x. Finally, the value of tmp which is 55,gets stored in x. So x is now 22 and x is 55. The x vector is now (33, 22, 55, 44, 11).
The j loop will now run again with j = 3, so x[j] = 55 and x[j+1] = 44. Because 55 > 44, the if condition will be TRUE. The two elements x[j] and x[j+1] will again be swapped and x will become (33, 22, 44, 55, 11).
The j loop will run one more time and you can work out what happens then.
Once the j loop has done its four iterations, the code prints the value of i and x, just so you can see how the algorithm progresses. Then i is changed to its next value and the whole j loop runs again.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.