• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Invert Array

 
Jae Lee
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello to all,

I was wondering if there was a way to invert an array.
(ie.


and the result will be
1
2
3
4
5


thank you
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean reverse the elements in an array using Standard Java Library classes?




Did you mean print the elements in reverseorder?



Did you mean this? This is not complete
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, there is. It is quite easy. Start by writing a method which swaps two elements in an array, like this
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harsha Smith wrote:You mean reverse the elements in an array using Standard Java Library classes? . . .
Probably not. That is a common homework assignment for newbies, working out how to do it by themselves.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also note that you only need to iterate over half of the array when you reverse it with swapping. After all, if you swap the first and last element, you then don't need to (or actually event want to) swap the last and the first. You essentially first swap the first and last, then the second and second-from-last, etc, until you hit the center.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic