Beispiel #1
0
   private static void StableSortInternal <T>(
       IList <T> list,
       int a,
       int n,
       IComparer <T> comparer,
       DeferredArray <T> tempArray)
   {
 #if DEBUG
       if (list == null)
       {
           throw new ArgumentNullException("list");
       }
       if (a < 0)
       {
           throw new ArgumentException("a (" + a + ") is less than 0");
       }
       if (a > list.Count)
       {
           throw new ArgumentException("a (" + a + ") is more than " + list.Count);
       }
       if (n < 0)
       {
           throw new ArgumentException("n (" + n + ") is less than 0");
       }
       if (n > list.Count)
       {
           throw new ArgumentException("n (" + n + ") is more than " + list.Count);
       }
       if (list.Count - a < n)
       {
           throw new ArgumentException("list's length minus " + a + " (" +
                                       (list.Count - a) + ") is less than " + n);
       }
       if (comparer == null)
       {
           throw new ArgumentNullException("comparer");
       }
 #endif
       int pl, pm;
       T   tmp;
       if (n < 7)
       {
           // Use insertion sort (already a stable sort)
           for (pm = a + 1; pm < a + n; ++pm)
           {
               for (pl = pm; pl > a && comparer.Compare(list[pl - 1], list[pl]) > 0; --pl)
               {
                   tmp          = list[pl];
                   list[pl]     = list[pl - 1];
                   list[pl - 1] = tmp;
               }
           }
           return;
       }
       var middle = n >> 1;
       StableSortInternal(list, a, middle, comparer, tempArray);
       StableSortInternal(list, a + middle, n - middle, comparer, tempArray);
       if (comparer.Compare(list[a + middle - 1], list[a + middle]) <= 0)
       {
           return;
       }
       var right = a + n;
       middle = a + middle;
       var temp = tempArray.GetArray();
       var i    = a;
       var j    = a;
       var k    = middle;
       while (j < middle && k < right)
       {
           // "<=" ensures stable sort
           var leq = comparer.Compare(list[j], list[k]) <= 0;
           temp[i++] = leq ? list[j++] : list[k++];
       }
       while (j < middle)
       {
           temp[i++] = list[j++];
       }
       for (i = a; i < k; ++i)
       {
           list[i] = temp[i];
       }
   }