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
| /** * 对Array对象的原型扩展来实现快速排序 * @param [left] 排序开始位置 * @param [right] 排序结束位置 * @returns {Array} */ Array.prototype.quickSort = function(left, right){ if(left === undefined) left = 0; //若left和right为空,设置初始值 if(right === undefined) right = this.length - 1; if(left < right){ var ref = this[left]; var low = left; var high = right; while(low < high){ //从右往左查询比ref小的值 while(low < high && this[high] > ref){ --high; } this[low] = this[high]; //从左往右查询比ref大的值 while(low < high && this[low] < ref){ ++low } this[high] = this[low]; } this[low] = ref; this.quickSort(low+1, right); this.quickSort(left, low-1); } return this; };
var arr1 = [95,8,65,98,54,25,3,654,4,74,63,88,35,68]; console.log(arr1.quickSort());
|