Skip to content

Instantly share code, notes, and snippets.

@StuPig
Created May 9, 2012 04:15
Show Gist options
  • Save StuPig/2641751 to your computer and use it in GitHub Desktop.
Save StuPig/2641751 to your computer and use it in GitHub Desktop.
Quicksort algorithm: javascript 实现的快速排序算法
// var times = 0;
// 快速排序算法
function quickSort(arr) {
if (!arr || Object.prototype.toString.call(arr).toLowerCase().indexOf('array') < 0) {
throw new Error('quickSort(): First arguments must be an Array.');
}
if (arr.length <= 1) {
return arr;
}
var length = arr.length
, pivotIndex = Math.floor(arr.length / 2)
, pivot = arr.splice(pivotIndex, 1)[0]
, left = []
, right = []
, i = 0
length -= 1
for (; i < length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
// times ++;
return quickSort(left).concat([pivot], quickSort(right));
}
var arr = [0,2,1,9,3,6,5,7,8,4,2]
console.log(quickSort(arr)); // [0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
// console.log(times); // 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment