Permalink
Browse files

[corlib] Fallback to Insertion Sort in the non-generic qsort()

Many thanks to Martin Potter <martin.potter@logos.com> for taking
the time to implement this, crossing it off of the long TODO list!
  • Loading branch information...
1 parent 9c9e2c6 commit 71bb64df713675bd40c62f3071a6d4cb86b3c94c @jstedfast jstedfast committed Aug 7, 2012
Showing with 27 additions and 2 deletions.
  1. +27 −2 mcs/class/corlib/System/Array.cs
@@ -1455,7 +1455,7 @@ static bool QSortArrange (Array keys, Array items, int lo, ref object v0, int hi
private static void qsort (Array keys, Array items, int low0, int high0, IComparer comparer)
{
QSortStack[] stack = new QSortStack[32];
- //const int QSORT_THRESHOLD = 7;
+ const int QSORT_THRESHOLD = 7;
int high, low, mid, i, k;
object key, hi, lo;
IComparable cmp;
@@ -1471,7 +1471,32 @@ private static void qsort (Array keys, Array items, int low0, int high0, ICompar
high = stack[sp].high;
low = stack[sp].low;
- // TODO: implement InsertionSort when QSORT_THRESHOLD reached
+ if ((low + QSORT_THRESHOLD) > high) {
+ // switch to insertion sort
+ for (i = low + 1; i <= high; i++) {
+ for (k = i; k > low; k--) {
+ lo = keys.GetValueImpl (k - 1);
+ hi = keys.GetValueImpl (k);
+ if (comparer != null) {
+ if (comparer.Compare (hi, lo) >= 0)
+ break;
+ } else {
+ if (lo == null)
+ break;
+
+ if (hi != null) {
+ cmp = hi as IComparable;
+ if (cmp.CompareTo (lo) >= 0)
+ break;
+ }
+ }
+
+ swap (keys, items, k - 1, k);
+ }
+ }
+
+ continue;
+ }
// calculate the middle element
mid = low + ((high - low) / 2);

0 comments on commit 71bb64d

Please sign in to comment.