+ 1

How to reverse an array?

Double[] oned={1.0,2.0,3.0,4.0}; reverse(oned); Arrays.toString(oned); //[4.0,3.0,2.0,1.0] public Stativ void reverse(Object[] array){ }

5th Nov 2016, 10:59 PM
valerkay
valerkay - avatar
3 Antworten
+ 2
public class Main { public static void main(String[] args) { Double[] oned={1.0,2.0,3.0,4.0}; Double[] reversed = reverse(oned); reversed.toString(); //[4.0,3.0,2.0,1.0] } public static Double[] reverse(Double[] array){ Double[] newArray = new Double[array.length]; for (int i=0;i<array.length;i++){ newArray[i]=array[array.length-i-1]; } return newArray; } } This is solution from my libs, but basically you can extend it to operate with any type. Anyway Sergiu's solution is the mostly used algorythm and I would recommend to use it if you don't want to create own libraries.
6th Nov 2016, 1:44 AM
Maksym Zieliński
Maksym Zieliński - avatar
+ 1
Do you want the final array to be a string? Anyways without any imported library or somesuch: int aux; for(int i = 0; i < oned.length / 2; i++) { aux = oned[i]; oned[i] = oned[oned.length - i - 1]; oned[oned.length - i - 1] = aux; } Basically swap elements in first half with those in second half ... The - 1 is because of the 0 based array system.
5th Nov 2016, 11:28 PM
Sergiu Lucec
Sergiu Lucec - avatar
+ 1
i create my own solution to reverse array of doubles thank you :)
7th Nov 2016, 4:00 AM
valerkay
valerkay - avatar