Nodejs Array Swap swap(i, j)

Here you can find the source of swap(i, j)

Method Source Code

'use strict';//from  w  ww  .  j  av a2  s. com

Array.prototype.swap = function (i, j) {
  const temp = this[i];
  this[i] = this[j];
  this[j] = temp;
}

function qsort (arr, lo=0, hi=arr.length - 1) {
  if (lo >= hi) return;
  
  arr.swap(lo, Math.floor(Math.random() * (hi - lo)) + lo);

  const pivot     = arr[lo];
  let   swapPoint = lo;

  for (let i = lo + 1; i <= hi; i++) {
    if (arr[i] < pivot) arr.swap(i, ++swapPoint);
  }
  arr.swap(lo, swapPoint);

  qsort(arr, lo, swapPoint - 1);
  qsort(arr, swapPoint + 1, hi);

  // return arr;
}

const testArr = [5,2,78,5,0,13,6];
qsort(testArr);
console.log(testArr);

Related

  1. swap(a,b)
    Array.prototype.swap = function(a,b){
      var tmp = this[a];
      this[a] = this[b];
      this[b] = tmp;
    
  2. swap(firstIndex, secondIndex)
    function bubbleSort(arr) {
      if (arr.length === 0 || arr.length === undefined) {
        return "No array as arg!"
      if (arr.length === 1) {
        return arr;
      var swapped = true;
      while (swapped) {
    ...
    
  3. swap(i, j)
    Array.prototype.swap = function(i, j) {
      var a = this[i];
      this[i] = this[j];
      this[j] = a;
    
  4. swap(i, j)
    Array.prototype.swap = function(i, j){
      var temp = this[i]
      this[i] = this[j]
      this[j] = temp
    
  5. swap(i, j)
    Array.prototype.swap = function (i, j) {
        var k = this[i]; this[i] = this[j]; this[j] = k;
    function bubbleSort(list) {
        var items = list.slice(0), swapped = false, p, q;
        for (p = 1; p < items.length; ++p) {
            for (q = 0; q < items.length - p; ++q) {
                if (items[q + 1] < items[q]) {
                    items.swap(q, q + 1);
    ...
    
  6. swap(i, j)
    Array.prototype.swap = function (i, j) {
        var tmp = this[i];
        this[i] = this[j];
        this[j] = tmp;
    };
    
  7. swap(i,j)
    Array.prototype.swap = function(i,j){
      var a = this;
      if(i!=j){
        a[j]^=a[i];
        a[i]^=a[j];
        a[j]^=a[i];
    
  8. swap(idx1, idx2)
    function quickSort(arr){
        function partition(low, high){
            if(high - low < 2){
                return
            var pivot = arr[low]
            var wall = low
            for(var i = low; i <= high; i++){
                if(arr[i] < pivot){
    ...
    
  9. swap(index1, index2)
    Array.prototype.swap = function(index1, index2) {
        var temp = this[index1];
        this[index1] = this[index2];
        this[index2] = temp;
    };