Nodejs Array Quick Sort quickSort(A)

Here you can find the source of quickSort(A)

Method Source Code

function quickSort(A) {
  if (A.length === 0) {
    return [];//from  w  w  w.  ja  v a2s  .com
  }
  if (A.length === 1 || (A.length === 2 && A[0] === A[1])) {
    return A;
  }
  let p = A.findBasePoint();
  let leftPart = [],
      rightPart = [];
  for (let i = 0; i < A.length; i++) {
    if (A[i] < p) {
      leftPart.push(A[i]);
    } else {
      rightPart.push(A[i]);
    }
  }
  return quickSort(leftPart).concat(quickSort(rightPart));
}

Array.prototype.findBasePoint = function() {
  let p = 0;
  if (this.length == 0) {
    return undefined;
  }
  for (let i = 0; i < this.length; i++) {
    p += this[i];
  }
  return p / this.length;
};


let unsortArray = [7, 5, 9, 12, 24, 12, 2, 1, 6, 5];
let sortArray = quickSort(unsortArray);
console.log(sortArray);
 5];
let sortArray = quickSort(unsortArray);
console.log(sortArray);

Related

  1. quickSort(a,start,end)
    'use strict'
    Array.prototype.showArray = function(){
        var temp = '';
        this.forEach(function(value,index){
            temp += value + " ";
        });
        if(typeof document !== "undefined"){
            document.body.innerHTML = temp;
        else{
            console.log(temp);
    };
    function partition(a,start,end){
        var i = start,j = end;
        var key = a[i];
        while(i<j){
            while(i<j && a[j] >= key){
                j--;
            if(i<j){
                var temp;
                temp = a[i];
                a[i] = a[j];
                a[j] = temp; 
            while(i<j && a[i] <= key){
                i++;
            if(i<j){
                var temp;
                temp = a[i];
                a[i] = a[j];
                a[j] = temp; 
        return i;
    function quickSort(a,start,end){
        var middle;
        if(start<end){
            middle = partition(a,start,end);
            quickSort(a,start,middle-1);
            quickSort(a,middle,end - 1);
    var a = [6,2,7,3,8,9];
    quickSort(a,0,5);
    a.showArray();
    
  2. quicksort(A, p, q)
    Array.prototype.swap = function(i, j) {
      var tmp = this[i];
      this[i] = this[j];
      this[j] = tmp;
    function partition(A, p, q, r) {
      var pivot = A[r];
      A.swap(r, p);
      var i = p;
    ...
    
  3. quicksort(A, p, r)
    "use strict";
    function main(A) {
        quicksort(A, 0, A.length - 1);
        console.log(A);
    function quicksort(A, p, r) {
        if (p < r) {
            var q = partition(A, p, r);
            quicksort(A, p, q - 1);
    ...
    
  4. quickSort()
    var quick = function(arr) {
      if(arr.length <= 1){
        return arr;
      var pivotIndex = Math.floor(arr.length / 2);
      var pivot = arr.splice(pivotIndex, 1)[0];
      var left = [];
      var right = [];
      var same = [];
    ...