How to sort cordinates?

Proper ways to do sorting in Java is by instantiating a Comparator w/ a compare() callback method:

Or defining a Comparable class w/ a compareTo() callback method:

But given you’re using 2 IntList containers already, and seems like the values within both x & y containers are within short and even the byte range, I’ve come up w/ a hackish solution which merges both containers as 1 container w/ same size() by using the bitshift operators << & >>; then call method sort() and then split the single container back to x & y containers:

/**
 * IntList XY Merge (v1.0.0)
 * GoToLoop (2025/Jan/15)
 * https://Discourse.Processing.org/t/how-to-sort-cordinates/45599/4
 */

final IntList
  x = new IntList(5, 3, 2, 4, 5), 
  y = new IntList(5, 4, 5, 4, 4);

final int[] xyArr = new int[2];

void setup() {
  println("input x:", x);
  println("input y:", y);

  final IntList xy = mergeXYLists(x, y, xyArr);
  println("unsorted xy:", xy);

  xy.sort();
  println("sorted xy:", xy);

  splitXYLists(xy, x, y, xyArr);
  println("sorted x:", x);
  println("sorted y:", y);

  exit();
}

static final int xyMerge(final int... xy) {
  return xy[0] << 16 | (char)xy[1];
}

static final int[] xySplit(final int xy) {
  return new int[] { xy >> 16, (short)(xy & 0xffff) };
}

static final int[] xySplit(final int xy, final int[] split) {
  split[0] = xy >> 16;
  split[1] = (short)(xy & 0xffff);
  return split;
}

static final IntList mergeXYLists(final IntList x, final IntList y) {
  return mergeXYLists(x, y, new int[2]);
}

static final IntList mergeXYLists
  (final IntList x, final IntList y, final int[] tmp)
{
  final int len = x.size();
  final IntList xy = new IntList(len);

  for (int i = 0; i < len; ++i) {
    tmp[0] = x.get(i);
    tmp[1] = y.get(i);
    xy.append(xyMerge(tmp));
  }

  return xy;
}

static final void splitXYLists
  (final IntList xy, final IntList x, final IntList y)
{
  splitXYLists(xy, x, y, new int[2]);
}

static final void splitXYLists
  (final IntList xy, final IntList x, final IntList y, final int[] tmp)
{
  final int len = xy.size();

  for (int i = 0; i < len; ++i) {
    xySplit(xy.get(i), tmp);
    x.set(i, tmp[0]);
    y.set(i, tmp[1]);
  }
}
input x: IntList size=5 [ 5, 3, 2, 4, 5 ]
input y: IntList size=5 [ 5, 4, 5, 4, 4 ]
unsorted xy: IntList size=5 [ 327685, 196612, 131077, 262148, 327684 ]
sorted xy: IntList size=5 [ 131077, 196612, 262148, 327684, 327685 ]
sorted x: IntList size=5 [ 2, 3, 4, 5, 5 ]
sorted y: IntList size=5 [ 5, 4, 4, 4, 5 ]
3 Likes