+ 1
try to reverse an array in Java
import java.util.Arrays; public class yo5 { public static void main(String[]args) { int[] a = new int[] {1,2,3,4,5}; int b = a.length; for(int i=0; i<a.length; i++) { b--; a[i] = a[b]; } System.out.println(Arrays.toString(a)); } } Can anyone explain why the outcome is [5, 4, 3, 4, 5] in stead of [5, 4, 3, 2, 1] ??
3 Answers
+ 2
You can reverse arrays without using additional memory
public static void reverseElementsInVector(double[] vector){
int size = vector.length - 1;
int medium = (size+1)/2;
for(int i = 0; i < medium; ++i){
swap(vector, i, size - i);
}
}
Swap function:
private static void swap(double[] vector, int i, int j){
double t = vector[i];
vector[i] = vector[j];
vector[j] = t;
}
+ 1
You can achieve it for example this way.
https://code.sololearn.com/cG6b0GyOtmn1/?ref=app