protected static int partition(Instances insts, int[] index, int attidx, int l, int r) {
    
    double pivot = insts.instance(index[(l + r) / 2]).value(attidx);
    int help;

    while (l < r) {
      while ((insts.instance(index[l]).value(attidx) < pivot) && (l < r)) {
        l++;
      }
      while ((insts.instance(index[r]).value(attidx) > pivot) && (l < r)) {
        r--;
      }
      if (l < r) {
        help = index[l];
        index[l] = index[r];
        index[r] = help;
        l++;
        r--;
      }
    }
    if ((l == r) && (insts.instance(index[r]).value(attidx) > pivot)) {
      r--;
    } 

    return r;
  }