Javascript Array Sort quick sort 2

Description

Javascript Array Sort quick sort 2

var arr = [5, 2, 4, 6, 1, 3];

console.log(arr);//from   w ww . jav a  2 s.c  om
console.log(quicksort(arr));

function quicksort(array) {
    var less = [], greater = [];
    var pivot;
    if(array.length <= 1) {
        return array;
    } else {
        pivot = array[0];
        var l = array.length;
        for(var i = 1; i < l; ++i) {
            if(array[i] < pivot) {
                less.push(array[i]);
            } else {
                greater.push(array[i]);
            }
        }
        var sorted = [];
        return sorted.concat(quicksort(less), pivot, quicksort(greater));
    }
}

Another implementation

function qSort(arr) {
  if (arr.length <= 1) {
    return arr;// w  w  w  .  ja va 2  s  .  c o m
  }

  var middle = arr[arr.length - 1];
  var lower = [];
  var higher = [];

  for (var i = 0;i < arr.length - 1;i++) {
    if (arr[i] <= middle) {
      lower.push(arr[i]);
    } else {
      higher.push(arr[i]);
    }
  }

  return qSort(lower).concat(middle).concat(qSort(higher));
}

console.log(qSort([4,2,4,6,2,4,1,22,41,7]));



PreviousNext

Related