+ 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){ }
3 ответов
+ 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.
+ 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.
+ 1
i create my own solution to reverse array of doubles
thank you :)