1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| function ArraySort(comparefn) {
var custom_compare = IS_FUNCTION(comparefn);
function Compare(x,y) { if (x === y) return 0; if (custom_compare) { return comparefn.call(null, x, y); } if (%_IsSmi(x) && %_IsSmi(y)) { return %SmiLexicographicCompare(x, y); } x = ToString(x); y = ToString(y); if (x == y) return 0; else return x < y ? -1 : 1; };
function InsertionSort(a, from, to) { for (var i = from + 1; i < to; i++) { var element = a[i]; var key = (custom_compare || %_IsSmi(element)) ? element : ToString(element); var min = from; var max = i; while (min < max) { var mid = min + ((max - min) >> 1); var order = Compare(a[mid], key); if (order == 0) { min = max = mid; break; } if (order < 0) { min = mid + 1; } else { max = mid; } } for (var j = i; j > min; j--) { a[j] = a[j - 1]; } a[min] = element; } }
function QuickSort(a, from, to) { if (to - from <= 22) { InsertionSort(a, from, to); return; } var pivot_index = $floor($random() * (to - from)) + from; var pivot = a[pivot_index]; var pivot_key = (custom_compare || %_IsSmi(pivot)) ? pivot : ToString(pivot); a[pivot_index] = a[from]; a[from] = pivot; var low_end = from; var high_start = to; for (var i = from + 1; i < high_start; ) { var element = a[i]; var order = Compare(element, pivot_key); if (order < 0) { a[i] = a[low_end]; a[low_end] = element; i++; low_end++; } else if (order > 0) { high_start--; a[i] = a[high_start]; a[high_start] = element; } else { i++; } } QuickSort(a, from, low_end); QuickSort(a, high_start, to); }
var old_length = ToUint32(this.length); if (old_length < 2) return this;
%RemoveArrayHoles(this);
var length = ToUint32(this.length);
for (var i = 0; i < length; ) { if (IS_UNDEFINED(this[i])) { length--; this[i] = this[length]; this[length] = void 0; } else { i++; } }
QuickSort(this, 0, length);
if (IS_ARRAY(this)) { this.length = old_length; }
return this; }
|