frito
frito

Reputation: 13

What is the Fastest way to reorder an array

What is the fastest (realtime data processing application) way to reorder (the new indices are always the same) an array in JAVA:

e.g.: I have got: double[] A = new double[] {1, 234, 12,99,0};

I need to get swiftly: double[] B = new double[] {A[2], A[4], A[0],A[1],A[3]};

But maybe this is this is the most efficient way to do it anyway?

many thanks for your feedback

Upvotes: 1

Views: 367

Answers (1)

Mark Elliot
Mark Elliot

Reputation: 77024

I doubt you can do better than your current approach of

double[] B = new double[] {A[2], A[4], A[0], A[1], A[3]};

Likely candidates for other sequences might be forms of Arrays.copyOf or Arrays.copyOfRange, but the minimum amount of work you must do here consists of:

  • create a new array
  • random access to each element in the array

There's a small chance that you might do slightly better with very specific read/write orders (to take advantage of cache lines), one guess is something that reads entirely in order and writes almost entire in ascending order:

   double[] B = new double[A.length];
   B[2] = A[0];
   B[3] = A[1];
   B[4] = A[3];
   B[0] = A[2];
   B[1] = A[4];

But I don't have strong expectations of this being noticeably better. If you're at the point where you're trying to eliminate or optimize on L1/L2 cache hits, it's time to start micro-benchmarking, and the real answer is you should experiment.

Upvotes: 1

Related Questions