javascript实现快速排序算法

忘记了快速排序的思路是怎样的了,复习一下,写了两个实例,发表博文备忘。

对于快速排序的思想,可以参考白话经典算法系列之六 快速排序 快速搞定,讲得比较通俗

prototype扩展的方式

/**
 * 对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());

非prototype方式

/**
 * @param array //要排序的数组
 * @returns {Array} //排完序的数组
 */
var quicksort = function(array){
    if(!array.length)   return array;
    var low = 0;
    var high = array.length - 1;
    var ref = array[low];
    while(low < high){
        while(low < high && array[high] > ref){
            --high;
        }
        array[low] = array[high];
        while(low < high && array[low] < ref){
            ++low
        }
        array[high] = array[low];
    }
    array[low] = ref;
    return quicksort(array.slice(0,low)).concat([ref],quicksort(array.slice(low+1, array.length)));
};

var arr2 = [95,8,65,98,54,25,3,654,4,74,63,88,35,68];
console.log(quicksort(arr2));
posted @ 2015-04-21 19:43  wayns  阅读(368)  评论(0编辑  收藏  举报