Results 1 to 2 of 2
  1. #1
    sara12345 is offline Member
    Join Date
    Dec 2009
    Posts
    59
    Rep Power
    0

    Default 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:(

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    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

Similar Threads

  1. Swapping elements of an array help please
    By ikillu in forum New To Java
    Replies: 11
    Last Post: 01-15-2012, 09:49 PM
  2. Binary Tree Traversals and Swapping
    By Sylar in forum New To Java
    Replies: 0
    Last Post: 03-08-2009, 08:52 AM
  3. compare newly added Vector Element with previous elements
    By nidhirastogi in forum Advanced Java
    Replies: 10
    Last Post: 09-10-2008, 02:32 AM
  4. Replies: 9
    Last Post: 07-10-2008, 05:52 PM
  5. Finding elements in a vector
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 09:37 PM

Posting Permissions

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