• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Swapping  RSS feed

 
haruki jay
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello- How come this code doesn't swap the values? How can i succesfully swap 2 values of an array?


 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Haruki,
That code is swapping the primitive parameter values. Those are sort of like copies. They don't affect the original array. For this to work properly, you need to pass the array and the two indexes to swap(). Then swap can actually update the array elements.
 
haruki jay
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:Haruki,
That code is swapping the primitive parameter values. Those are sort of like copies. They don't affect the original array. For this to work properly, you need to pass the array and the two indexes to swap(). Then swap can actually update the array elements.


Thank you for your answer!
In order to pass the array and both values, would it work by using a for loop, as i would to print or go through the values of an array?
I am not sure how to go about this question.

 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
haruki jay wrote:In order to pass the array and both values, would it work by using a for loop, as i would to print or go through the values of an array?

One thing at a time.

You misunderstood. At the moment you are solving problem of swapping array elements.

What you have been suggested, was to have a method something like:

where i and j are indices of elements you want to swap within an array.

The implementation part is kinda very similar to what you had, but this time you just need to operate on the passed in to the method array.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!