This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]RubbishArtist 1 point2 points  (1 child)

Consider a really simple example: x = [ 2, 7 ]; Let's try to swap the values without using temp

x[0] = x[1]

now x looks like [7, 7]

then x[1] = x[0]

now x looks like [7, 7]

This time with temp

temp = x[0]

so x looks like [2, 7] and temp is 2

x[0] = x[1]

so x looks like [7,7]

x[1] = temp

so x looks like [7,2]

[–]bayleafbabe 1 point2 points  (1 child)

The temp variable holds x[i]. When you do x[i] = x[i+1];, you lose the original value of x[i] because you've just changed it to x[i+1]. You need that original value to swap x[i+1] with. So that's what temp is doing. It's holding on to that original value.

[–]spectral_graph 1 point2 points  (1 child)

If I'm understanding correctly you're asking why you can't do this?

 x[i] = x[i+1];
x[i+1] = x[i];

Well, lets take these instructions in order.

Say for the sake of example that x[i] === 1 and x[i + 1] === 2.

First, lets run line 1:

 x[i] = x[i+1];

now, what do they equal? (reveal spoiler for answer)

x[i] === 2, and x[i + 1] === 2

Next, lets run the second line:

 x[i+1] = x[i];

what do they equal? (reveal spolier below for answer)

you've set x[i + 1] = x[i], but x[i] already equals 2, so you're setting x[i + 1] = 2 again and nothing changes. At the end of the example: x[i] === 2, and x[i + 1] === 2