Sorting an array

// https://Discourse.processing.org/t/sorting-an-array/20992/4
// GoToLoop (2020/May/18)

import java.util.Arrays;
import java.util.Comparator;

final PVector[] vecs = {
  new PVector(100, -100), 
  new PVector(-130, 65), 
  new PVector(135, 155)
};

static final Comparator<PVector> HEADING = new Comparator<PVector>() {
  @Override final int compare(final PVector a, final PVector b) {
    return (int) Math.signum(a.heading() - b.heading());
  }
};

static final Comparator<PVector> HEADING_REVERSED = HEADING.reversed();

void setup() {
  println(vecs);
  printVecHeadings();
  println();

  Arrays.sort(vecs, HEADING);  // ascending
  println(vecs);
  printVecHeadings();
  println();

  Arrays.sort(vecs, HEADING_REVERSED);  // descending
  println(vecs);
  printVecHeadings();

  exit();
}

void printVecHeadings() {
  for (final PVector v : vecs)  print(v.heading() + "              ");
}
3 Likes