How to "copy" an array operation to another array?

This is probably a simple question, but I have two arrays of about 1000 elements each, they are called posXArray and posYArray . I want to sort posYArray numerically (the lowest number first), but I want posXArray elements posXArray apply the same operation to them ...

For example, if the [56] of posYArray is the smallest, I want the [56] of posXArray also be moved to [0].

How is this implemented in Java in simple / good form?

Thank you so much for your help!

+6
source share
4 answers

Create a class like:

 public class XYPos implements Comparable<XYPos> { int x; int y; @Override public int compareTo(XYPos o) { int res = this.y - oy; if(res == 0) { res = this.x - ox; } return res; } } 

Then:

  • convert 2 arrays into one XYPos array
  • sort it
  • update 2 source arrays with values ​​in a sorted array
+2
source

Since arrays seem to contain X and Y coordinates, maybe the best choice is to create a coordinate class containing both values, implement Comparable and just have one array to sort using the built-in algorithms?

+8
source

Create an Integer[] idx the same length and fill it with numbers from 0 to 999 (or something else), then sort this array using a comparator that does

 public int compare(Integer a, Integer b) { return posYArray[a] - posYArray[b]; } 

This will give you an array of indices in other arrays, i.e. the smallest value of Y will be posYArray[idx[0]] , and its corresponding X will be posXArray[idx[0]] , etc. If you don't want to maintain indirection, you can reorder the original arrays with idx values.

If you regularly do such things, you can look at fastutil , which provides Collection and Comparator types that work directly on primitive types such as int , avoiding the need to insert integers into the box and Unbox.

+1
source

You can implement any sorting algorithm of your choice, perform a matching check only for the first one (posXArray), and then change the positions of the elements in both arrays at the same time.

0
source

All Articles