private static void DownHeap(IndexedSortable s, int b, int i, int N) { for (int idx = i << 1; idx < N; idx = i << 1) { if (idx + 1 < N && s.Compare(b + idx, b + idx + 1) < 0) { if (s.Compare(b + i, b + idx + 1) < 0) { s.Swap(b + i, b + idx + 1); } else { return; } i = idx + 1; } else { if (s.Compare(b + i, b + idx) < 0) { s.Swap(b + i, b + idx); i = idx; } else { return; } } } }
private static void Fix(IndexedSortable s, int p, int r) { if (s.Compare(p, r) > 0) { s.Swap(p, r); } }
public virtual int Compare(int i, int j) { Assert.True("Expected fewer than " + maxcmp + " comparisons", ++ comparisions < maxcmp); return(s.Compare(i, j)); }
private static void SortInternal(IndexedSortable s, int p, int r, Progressable rep , int depth) { if (null != rep) { rep.Progress(); } while (true) { if (r - p < 13) { for (int i = p; i < r; ++i) { for (int j = i; j > p && s.Compare(j - 1, j) > 0; --j) { s.Swap(j, j - 1); } } return; } if (--depth < 0) { // give up alt.Sort(s, p, r, rep); return; } // select, move pivot into first position Fix(s, (int)(((uint)(p + r)) >> 1), p); Fix(s, (int)(((uint)(p + r)) >> 1), r - 1); Fix(s, p, r - 1); // Divide int i_1 = p; int j_1 = r; int ll = p; int rr = r; int cr; while (true) { while (++i_1 < j_1) { if ((cr = s.Compare(i_1, p)) > 0) { break; } if (0 == cr && ++ll != i_1) { s.Swap(ll, i_1); } } while (--j_1 > i_1) { if ((cr = s.Compare(p, j_1)) > 0) { break; } if (0 == cr && --rr != j_1) { s.Swap(rr, j_1); } } if (i_1 < j_1) { s.Swap(i_1, j_1); } else { break; } } j_1 = i_1; // swap pivot- and all eq values- into position while (ll >= p) { s.Swap(ll--, --i_1); } while (rr < r) { s.Swap(rr++, j_1++); } // Conquer // Recurse on smaller interval first to keep stack shallow System.Diagnostics.Debug.Assert(i_1 != j_1); if (i_1 - p < r - j_1) { SortInternal(s, p, i_1, rep, depth); p = j_1; } else { SortInternal(s, j_1, r, rep, depth); r = i_1; } } }