sorting/insertionsort.js

  1. (function (exports) {
  2. 'use strict';
  3. function compare(a, b) {
  4. return a - b;
  5. }
  6. /**
  7. * Insertionsort algorithm.<br><br>
  8. * Time complexity: O(N^2).
  9. *
  10. * @example
  11. *
  12. * var sort = require('path-to-algorithms/src' +
  13. * '/sorting/insertion-sort').insertionSort;
  14. * console.log(sort([2, 5, 1, 0, 4])); // [ 0, 1, 2, 4, 5 ]
  15. *
  16. * @public
  17. * @module sorting/insertionsort
  18. * @param {Array} array Input array.
  19. * @param {Function} cmp Optional. A function that defines an
  20. * alternative sort order. The function should return a negative,
  21. * zero, or positive value, depending on the arguments.
  22. * @return {Array} Sorted array.
  23. */
  24. function insertionSort(array, cmp) {
  25. cmp = cmp || compare;
  26. var current;
  27. var j;
  28. for (var i = 1; i < array.length; i += 1) {
  29. current = array[i];
  30. j = i - 1;
  31. while (j >= 0 && cmp(array[j], current) > 0) {
  32. array[j + 1] = array[j];
  33. j -= 1;
  34. }
  35. array[j + 1] = current;
  36. }
  37. return array;
  38. }
  39. exports.insertionSort = insertionSort;
  40. })(typeof window === 'undefined' ? module.exports : window);