Tuning quick sort.

Tuning the quick sort algorithm to avoid degenerating to an n^2 algorithm when all elements are the same.
Review URL: http://codereview.chromium.org/4083

git-svn-id: http://v8.googlecode.com/svn/branches/bleeding_edge@378 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
This commit is contained in:
olehougaard 2008-09-25 13:21:56 +00:00
parent 20e3e2f85f
commit 83da47e0d8

View File

@ -647,7 +647,7 @@ function ArraySplice(start, delete_count) {
function ArraySort(comparefn) { function ArraySort(comparefn) {
// Standard in-place HeapSort algorithm. // In-place QuickSort algorithm.
function Compare(x,y) { function Compare(x,y) {
if (IS_UNDEFINED(x)) { if (IS_UNDEFINED(x)) {
@ -672,21 +672,26 @@ function ArraySort(comparefn) {
if (from >= to - 1) return; if (from >= to - 1) return;
var pivot_index = $floor($random() * (to - from)) + from; var pivot_index = $floor($random() * (to - from)) + from;
var pivot = a[pivot_index]; var pivot = a[pivot_index];
a[pivot_index] = a[to - 1]; var low_end = from; // Upper bound of the elements lower than pivot.
a[to - 1] = pivot; var high_start = to; // Lower bound of the elements greater than pivot.
var partition = from; for (var i = from; i < high_start; ) {
for (var i = from; i < to - 1; i++) {
var element = a[i]; var element = a[i];
if (Compare(element, pivot) < 0) { var order = Compare(element, pivot);
a[i] = a[partition]; if (order < 0) {
a[partition] = element; a[i] = a[low_end];
partition++; a[low_end] = element;
low_end++;
i++;
} else if (order > 0) {
high_start--;
a[i] = a[high_start];
a[high_start] = element;
} else { // order == 0
i++;
} }
} }
a[to - 1] = a[partition]; QuickSort(a, from, low_end);
a[partition] = pivot; QuickSort(a, high_start, to);
QuickSort(a, from, partition);
QuickSort(a, partition + 1, to);
} }
var old_length = ToUint32(this.length); var old_length = ToUint32(this.length);