Javascript Array quickSort(arr)

Description

Javascript Array quickSort(arr)

// quick sort/*from   w w  w . j  a v a 2  s .  co m*/
Array.prototype.quickSwap = function(idx1, idx2) {
  var temp = this[idx1];
  this[idx1] = this[idx2];
  this[idx2] = temp;

  return this;
};

var quickSort = function(arr) {

  var placePivot = function(start, end) {
    if (start >= end) {
      return;
    }

    var mid = start;
    for (var i = start; i < end; i++) {
      if (arr[i] < arr[end]) {
        arr.quickSwap(mid, i);
        mid++;
      }
    }

    arr.quickSwap(mid, end);
    placePivot(start, mid - 1);
    placePivot(mid + 1, end);
  }

  placePivot(0, arr.length - 1);
  return arr;
};



PreviousNext

Related