UNPKG

dist-javascript-algorithms-and-data-structures

Version:

Algorithms and data-structures implemented on JavaScript

39 lines (27 loc) 1.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _Sort = _interopRequireDefault(require("../Sort")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class InsertionSort extends _Sort.default { sort(originalArray) { const array = [...originalArray]; // Go through all array elements... for (let i = 0; i < array.length; i += 1) { let currentIndex = i; // Call visiting callback. this.callbacks.visitingCallback(array[i]); // Go and check if previous elements and greater then current one. // If this is the case then swap that elements. while (array[currentIndex - 1] !== undefined && this.comparator.lessThan(array[currentIndex], array[currentIndex - 1])) { // Call visiting callback. this.callbacks.visitingCallback(array[currentIndex - 1]); // Swap the elements. const tmp = array[currentIndex - 1]; array[currentIndex - 1] = array[currentIndex]; array[currentIndex] = tmp; // Shift current index left. currentIndex -= 1; } } return array; } } exports.default = InsertionSort;