Swapping Elements in an Array
array |
2 |
5 |
12 |
9 |
8 |
18 |
15 |
|
|
|
↑ |
|
↑ |
|
|
indices |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
|
|
|
index1 |
|
index2 |
|
|
index1 = 2;
index2 = 4;
What if we want to swap the entries at indices 2 and 4?
var temp = index1;
index1 = index2;
index2 = temp;
array |
2 |
5 |
12 |
9 |
8 |
18 |
15 |
|
|
|
↑ |
|
↑ |
|
|
indices |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
|
|
|
index2 |
|
index1 |
|
|
|
|
|
index1 |
|
index2 |
|
|
No! We want to swap the entries __at__ indices 2 and 4!
index1 = 2;
index2 = 4;
var temp = array[index1];
array[index1] = array[index2];
array[index2 ]= temp;
array |
2 |
5 |
8 |
9 |
12 |
18 |
15 |
|
|
|
↑ |
|
↑ |
|
|
indices |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
|
|
|
index1 |
|
index2 |
|
|