@@ -116,7 +116,9 @@ mergeSort = algos.mergeSort = function (list) {
116116
117117 var swap,
118118 partition,
119- quickSort;
119+ quickSort,
120+ randomizedPartition,
121+ randomizedQuickSort;
120122
121123
122124 // easy peasy swap function.
@@ -198,6 +200,60 @@ quickSort = algos.quickSort = function (list, left, right) {
198200 return list;
199201 };
200202
203+// This version of partition and quick sort calculates the pivot at random,
204+// since the probability of the randomizer finding an item in the list that divides
205+// the list in a 25-75 split is superior.
206+// The expected time requirement becomes O(n log n), and the worst-case O(n^2) is very
207+// unlikely to happen
208+
209+// var randomizedPartition,
210+ // randomizedQuickSort;
211+
212+randomizedPartition = function (list, left, right) {
213+ var pivot = list[Math.floor(Math.random() * (right - left) + left)];
214+
215+ while (left <= right) {
216+
217+ while (list[left] < pivot) {
218+ left += 1;
219+ }
220+
221+ while (list[right] > pivot) {
222+ right -= 1;
223+ }
224+
225+ if (left <= right) {
226+ swap(list, left, right);
227+ left += 1;
228+ right -= 1;
229+ }
230+
231+ }
232+
233+ return left;
234+};
235+
236+randomizedQuickSort = algos.randomizedQuickSort = function (list, left, right) {
237+ var idx;
238+
239+ if (list.length >= 2) {
240+
241+ left = left === undefined ? 0 : left;
242+ right = right === undefined ? list.length - 1 : right;
243+
244+ idx = randomizedPartition(list, left, right);
245+
246+ if (left < idx - 1) {
247+ randomizedQuickSort(list, left, idx - 1);
248+ }
249+
250+ if (idx < right) {
251+ randomizedQuickSort(list, idx, right);
252+ }
253+ }
254+
255+ return list;
256+};
201257
202258
203259 // Bubble sort, aka blubbly