# Thread: swapping elements of vector

1. Member Join Date
Dec 2009
Posts
59
Rep Power
0

## swapping elements of vector

hello
I need to swap elements of vector but without redunducy. for example swapping elements 1 with 2 is the same as swapping element 2 with 1 so I don't want to save the second result I want to save it only one time
my code is the following :
Java Code:
```			for( int x=0;x<v1size();x++)	{
for ( int w=0;w< v1.size();w++){
Collections.swap(v1, x, w);```
but the above code will swap with redunducy:(  Reply With Quote

2. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## One way of calling each of the (size*(size+1))/2 distinct pairs of list indices would be

Java Code:
```for(int x = 0; x<v1.size(); x++) {
for(int w = x; w< v1.size();w++) {```

ie swap an index position with those to its right.

Do you realise that once you call Collections.swap() the index positions now refer to different objects? That's why I said that the code above was one way of doing it. If you do all the (size*(size+1))/2 swaps in a different order you will end up with a different result. And you haven't described the result you want!

As an example of this, consider a list of three objects:

A B C

There are exactly three swaps possible (0,1)=(1,0) (0,2)=(2,0) (1,2)=(2,1). If we follow the "swap to the right" rule we get

A B C (0,1) --> B A C
B A C (0,2) --> C A B
C A B (1,2) --> C B A

But if we do the same three "non redundant" swaps in a different order we get

A B C (1,2) --> A C B
A C B (0,1) --> C A B
C A B (0,2) --> B A C  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•