Mergesort for Processing and Processing.js

Since Processing.js does not support Java’s Arrays.sort or Collections.sort, I recommend writing your own sort. Here’s an example mergesort:
class Inters {
 float ang = random(0,10);
}

void setup() {
 ArrayList<Inters> x = new ArrayList<Inters>();
 for(int i = 0 ; i < 20; i++) x.add(new Inters());
 mergesort(x);
 for(int i = 0; i < x.size(); i++) println(x.get(i).ang);
}

void mergesort(ArrayList<Inters> inters) {
 if(inters.size() <= 1) return;

 ArrayList<Inters> left = new ArrayList<Inters>();
 ArrayList<Inters> right = new ArrayList<Inters>();
 for(int i = 0 ; i < inters.size(); i++) {
   if(i < inters.size() / 2) left.add(inters.get(i));
   else right.add(inters.get(i));
 }

 mergesort(left);
 mergesort(right);

 for(int i=0,j=0,k=0; i < inters.size(); i++) {
   if(k >= right.size() || (j < left.size() && left.get(j).ang < right.get(k).ang)) {
     inters.set(i, left.get(j++));
   }else {
     inters.set(i, right.get(k++));
   }
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *