Skip to content

Commit

Permalink
Merge pull request #2 from lucher/master
Browse files Browse the repository at this point in the history
[TimSort] handle empty child array
  • Loading branch information
leonchen83 authored Dec 29, 2023
2 parents d5605da + 01d6845 commit e4c4e2d
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions src/main/java/cn/nextop/TimArrSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,29 @@ public class TimArrSort<T> {
private static final int INITIAL_TMP_LENGTH = 256;

private TimArrSort(List<T[]> a, Comparator<? super T> c) {
this.a = a; this.c = c; this.lens = new int[a.size()]; /* init */
int i = 0; for (T[] t : a) { length += t.length; lens[i++] = length; }
this.a = a; this.c = c; this.lens = new int[a.size()]; this.init();
/* Allocate temp storage (which may be increased later if necessary) */
int l = INITIAL_TMP_LENGTH; int t = (length < 2 * l) ? length >>> 1 : l;
this.tmp = (T[]) newInstance(a.get(0).getClass().getComponentType(), t);
int sl = (length < 120 ? 5 : length < 1542 ? 10 : length < 119151 ? 24 : 49);
this.tmpLen = t; this.runBase = new int[sl]; runLen = new int[sl]; /* run! */
}

private void init() {
int i = 0; for (T[] t : a) {
final int l = t.length;
length += l; lens[i++] = length;
if(l == 0) this.hasEmpty = true;
} if (this.hasEmpty) this.initLoc();
}

/**
* Sorts the given range
*/
public static <T> void sort(List<T[]> a, Comparator<? super T> c) {
final TimArrSort<T> ts = new TimArrSort<>(a, c);
int base = 0; for (T[] t : a) { int l = t.length;
if(l == 0) { ts.hasEmpty = true; continue; }
var ts = new TimArrSort(a, c);
int base = 0; for (T[] t : a) {
int l = t.length; if (l == 0) continue;
int rl = countRunAndMakeAscending(t, 0, l, c);
if (rl < l) { binarySort(t, 0, l, rl, c); rl = l; }
ts.pushRun(base, rl); ts.mergeCollapse(); base += rl;
Expand Down Expand Up @@ -256,11 +263,7 @@ private T get(int i) { /* for read */
}

private void set(T s) { /* for write */
if(hasEmpty) { /* contains empty array */
int rs = this.lens.length - 1;/* last row */
while (row2 < rs && lens[row2] == 0) row2++;
if (row2 == rs && this.lens[row2] == 0) return;
} this.a.get(row2)[col2] = s; /* set current value */
this.a.get(row2)[col2] = s;
}

private void prev(int n) { /* for read */
Expand Down Expand Up @@ -299,6 +302,19 @@ private void next2(int n) { /* for write */
} else col2 += n; index2 = i;
}

private void initLoc() {
this.skipEmpty();
this.row2 = row3 = row;
this.col2 = col3 = col;
index2 = index3 = index;
}

private void skipEmpty() { /* skip */
int rs = lens.length - 1;/* last row */
while (row < rs && lens[row] == 0) row++;
assert !(row == rs && this.lens[row] == 0);
}

private void locate(int i) { /* for read */
if (i == index) return;
if (hasCache(i)) return;
Expand Down

0 comments on commit e4c4e2d

Please sign in to comment.