Nodejs Array Quick Sort quickSort(a,start,end)

Here you can find the source of quickSort(a,start,end)

Method Source Code

'use strict'//  www . jav  a  2 s . c  o  m

Array.prototype.showArray = function(){
    var temp = '';
    this.forEach(function(value,index){
        temp += value + " ";
    });
    
    // if the enviroment is browser
    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){
        // from right to left
        while(i<j && a[j] >= key){
            j--;
        }
        if(i<j){
            var temp;
            temp = a[i];
            a[i] = a[j];
            a[j] = temp; 
        }
        
        // from left to right
        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();

Related

  1. quickSort(A)
    function quickSort(A) {
      if (A.length === 0) {
        return [];
      if (A.length === 1 || (A.length === 2 && A[0] === A[1])) {
        return A;
      let p = A.findBasePoint();
      let leftPart = [],
    ...
    
  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 = [];
    ...
    
  5. quickSort()
    Array.prototype.quickSort = function() {
      var len = this.length
      if(len > 1) {
        var pivot = this[0]
        var left = []
        var right = []
        for(var i = 1; i < len; i++) {
          if(this[i] < pivot) {
            left.push(this[i])
    ...