You have to use an intermediary variable: assign it the value at one index, assign the value at the other index to the location at the first index, then assign to the location of the second index the value of the intermediary variable.
You can make a function to do this.
Try searching swap, from the main site.
Perhaps I was not clear in my post when I said swap an element with itself this doesn't mean two different elements with the same value it means the same position in the array.
To me an element in an array is a single variable referenced by an index. The value stored in the element can be anything that matches the data type of the array.
So in my code if idxa == idxb the the value stored at that location will be changed to 0 (zero). If idxa != idxb then the integer values stored in these two elements will be swapped, although there will be no visible change if the 2 values are equal.
Answers
You have to use an intermediary variable: assign it the value at one index, assign the value at the other index to the location at the first index, then assign to the location of the second index the value of the intermediary variable.
You can make a function to do this.
Try searching swap, from the main site.
An advanced swap algorithm for integer values using the xor
^
operator: :-bd@GoToLoop, that can make an element's value turn to 0:
@asimes initially I made no sense of your code then I saw what you are getting at.
You are right in that if you attmpt to swap an element with itself then the element will become 0 because any integer xor'd with itself will be zero.
In this code if you change idxa to 2 then the 15 becomes zero
@quark, actually it is more specific than that. Try out the same indices as above (0 and 2) with this array:
It still works, both 5s remain. The problem is that when the indices are the same the same memory location is modified
@asimes I am aware of everything you said.
Perhaps I was not clear in my post when I said swap an element with itself this doesn't mean two different elements with the same value it means the same position in the array.
To me an element in an array is a single variable referenced by an index. The value stored in the element can be anything that matches the data type of the array.
So in my code if
idxa == idxb
the the value stored at that location will be changed to 0 (zero). Ifidxa != idxb
then the integer values stored in these two elements will be swapped, although there will be no visible change if the 2 values are equal.Beside, the OP didn't mention integers, so the fancy trick is of limited usefulness...
You only need one temporary variable.
var b = list[y]; list[y] = list[x]; list[x] = b;
That's true. However it is also true that in order to have a "temporary" swap variable,
we gotta need the array's data type either way! (%)
At least the "fancy" way would work for any fixed-point data type! Perhaps even
boolean
! :D