简体   繁体   中英

How to write shell sort on Node.js

I'm trying to write a shellsort on Node.js like on the book Algorithms, 4th ed. Sedgewick, Wayne. There all the examples written on Java.

Here is my module:

"use strict";

module.exports = (function() {

  function sort(array) {
    let size = array.length;
    let h = 1;
    while(h < size/3) {
      h = h * 3 + 1;
    }
    while(h >= 1) {
      for(let i = h; i < size; i++) {
        for(let j = i; j >= h && less(array, j, j-h); j = j-h) {
          exch(array, j, j-h);
        }
      }
      h = h/3;
    }
  }

  function less(array, i, min) {
    return array[i] < array[min];
  }

  function exch(array, i, min) {
    let temp = array[i];
    array[i] = array[min];
    array[min] = temp;
  }

  return {
    sort: sort
  };

})();

I use mocha and chai for testing with this function:

function isSorted(array) {
  for(let i = 1, size = array.length; i < size; i++) {
    if (array[i] < array[i-1]) {
      return false;
    }
  }
  return true;
}

and shell sort not working: mocha test screenshot

Implementation of shell sort algorithm in Javascript

function shellSort(arr){

    var len  = arr.length;
    var gapSize =  Math.floor(len/2);

    while(gapSize > 0){
        for(var i = gapSize; i < len; i++) {

            var temp = arr[i];
            var j = i;

            while(j >= gapSize && arr[j - gapSize] > temp) {
                arr[j] = arr[j - gapSize];
                j -= gapSize;
            }
            arr[j] = temp;
        }
        gapSize = Math.floor(gapSize/2);
    }
    return arr;
}

function isSorted(array) {
  for(let i = 1, size = array.length; i < size; i++) {
    if (array[i] < array[i-1]) {
      return false;
    }
  }
  return true;
}


var randomArray = [45,86,3,5,97,95,4,24,7,88,93,27,45,90,54,89,74,5,90,73,74,857,834,8394,4231,485,32,54,674,12];
var mySortedArray = shellSort(randomArray);

console.log(mySortedArray);
console.log(isSorted(mySortedArray));

Output:

[3, 4, 5, 5, 7, 12, 24, 27, 32, 45, 45, 54, 54, 73, 74, 74, 86, 88, 89, 90, 90, 93, 95, 97, 485, 674, 834, 857, 4231, 8394]
true

Your h may become a floating point number if you use h = h / 3 . Try h = Math.floor(h / 3); instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM