wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Invert Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Invert Array" Watch "Invert Array" New topic
Author

Invert Array

Jae Lee
Greenhorn

Joined: Jun 10, 2011
Posts: 5
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

Joined: Jul 18, 2011
Posts: 287
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

Joined: Oct 13, 2005
Posts: 37907
    
  22
Yes, there is. It is quite easy. Start by writing a method which swaps two elements in an array, like this
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37907
    
  22
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

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Invert Array
 
Similar Threads
simple sorting algorithm
More Array sorting trouble
Static....
Arrays.sort(int[], int, int)
Oh gosh, i think it's a BUG ?!