4 *new { arg size = 8, function;
5 function = function ? { arg a, b; a < b }
6 ^super.new(size).function_(function)
14 nextIndex = this.indexForInserting(item);
15 this.insert(nextIndex, item);
17 addAll { arg aCollection;
18 aCollection = aCollection.asCollection;
19 if ( aCollection.size > (this.size div: 3), {
20 // Faster to add the new elements and resort
21 aCollection.do({ arg each; super.add(each) });
23 },{ // Faster to add the elements individually in their proper places
24 aCollection.do({ arg each; this.add(each) });
28 copyRange { arg start, end; ^this.class.newUsing(array.copyRange(start, end)).function_(function) }
29 copySeries { arg first, second, last;
30 ^this.class.newUsing(array.copySeries(first, second, last)).function_(function)
34 indexForInserting { arg newObject;
37 var high = this.size-1;
39 index = high + low div: 2;
42 if (function.value(array.at(index), newObject), {
51 sort { this.sortRange(0, array.size - 1) }
54 //Sort elements i through j of this to be nondescending according to
57 var di, dij, dj, tt, ij, k, l, n;
58 // The prefix d means the data at that index.
59 if ((n = j + 1 - i) <= 1, { ^this }); // Nothing to sort.
64 if (function.value(di, dj).not, { // i.e., should di precede dj?
70 if ( n > 2, { // More than two elements.
71 ij = (i + j) div: 2; // ij is the midpoint of i and j.
72 dij = array.at(ij); // Sort di,dij,dj. Make dij be their median.
73 if (function.value(di, dij), { // i.e. should di precede dij?
74 if (function.value(dij, dj).not, { // i.e., should dij precede dj?
78 },{ // i.e. di should come after dij"
82 if ( n > 3, { // More than three elements.
83 // Find k>i and l<j such that dk,dij,dl are in reverse order.
84 // Swap k and l. Repeat this procedure until k and l pass each other.
90 k <= l and: { function.value(dij, array.at(l)) }
91 }); // i.e. while dl succeeds dij
94 k <= l and: { function.value(array.at(k), dij) };
95 }); // i.e. while dij succeeds dk
100 // Now l<k (either 1 or 2 less), and di through dl are all less than or equal to dk
101 // through dj. Sort those two segments.
102 this.sortRange(i, l);
103 this.sortRange(k, j);