一个数组,比如:

[3,9,2,1,5,4]

取出某个元素(比如第一个元素3);

将除3之外的元素元素分为两组,小于(less than)等于(equal)3的为一组,[1,2],记为lt,大于(greater than)3的为一组[4,5,9] ,记为gt;

对lt 和 gt 重复上面的步骤——快速排序是一个递归过程(recursive);

将最终的结果合并。

用js来描述就是:

  // list that greater than n
  function listgt(list,n){
    return list.filter(function(m){
             return m > n;
           })
  }
  // eg.
  // 返回大于2的元素
  // -> [ 3, 9, 5, 4 ]
  // console.log(listgt([3,9,2,1,5,4],2));
  
  
  // list that less than or equal to n
  function listlet(list,n){
    return list.filter(function(m){
             return m <= n;
           })
  }
  // eg.
  // 返回比小于或等于2的元素
  // -> [ 2, 1 ]
  // console.log(listlet([3,9,2,1,5,4],2));
  
  function first(list){
    return list[0];
  }
  function rest(list){
    return list.slice(1);
  }
  
  function quicksort(list){
    if(list.length === 0){
      return [];
    }else{
      var n = first(list)
        , lt = listlet(rest(list),n)
        , gt = listgt(rest(list),n)
  
      // 递归 & 合并
      return [].concat(quicksort(lt)
                      ,n
                      ,quicksort(gt))
    }
  }
  console.log(quicksort([3,9,2,1,5,4]));
  // [ 1, 2, 3, 4, 5, 9 ]

 

posted on 2013-06-30 22:17  wewe.Tom  阅读(1311)  评论(0编辑  收藏  举报