Java – how to invert large arrays?
•
Java
OK, so I know it's very easy to reverse the array by swapping items until you reach the middle like this:
int array[SIZE]; int temp; for (int i = 0; i < SIZE/2; i++) { temp = array[i]; array[i] = array[SIZE-1 - i]; array[SIZE-1 - i] = temp; }
But what if the array size is really as big as 10000? Is it possible to do o (n)?
Solution
You can't complete it faster than the current algorithm you run in O (n) You may be interested in wrapping arrays in classes that provide o (1) inversion:
A simple version might look like this:
public class ReversableArray { private boolean reverse = false; private final int[] array; public ReversableArray(int[] array) { this.array = array; } public int get(int index) { return reverse ? array[array.length - index - 1] : array[index]; } public void reverse() { reverse = !reverse; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码