Quick sort an array - Node.js Algorithm

Node.js examples for Algorithm:Sort

Description

Quick sort an array

Demo Code

Array.prototype.quickSort = function () {
  if(this.length <= 1) {
    return this;//from   w  ww .  j ava 2 s.c  o m
  }
  var pivotIndex = ~~(this.length / 2);
  var pivot = this[pivotIndex];

  var less = [];
  var greather = [];

  for (var i = 0; i < this.length; i++) {
    if(this[i] < pivot) {
      less.push(this[i]);
    }
    if(this[i] > pivot) {
      greather.push(this[i]);
    }
  }

  this.length = 0;
  this.push.apply(this, less.quickSort());
  this.push(pivot);
  this.push.apply(this, greather.quickSort());

  return this;
}

Array.prototype.functionalQuickSort = function () {
  if(this.length <= 1) {
    return this;
  }
  var pivotIndex = ~~(this.length / 2);
  var pivot = this[pivotIndex];

  var sorted = this.filter(function (item) { return item < pivot }).functionalQuickSort().concat([pivot]).concat(
               this.filter(function (item) { return item > pivot }).functionalQuickSort());

  this.length = 0;
  this.push.apply(this, sorted);
  return this;
}

Related Tutorials