UNPKG

dist-javascript-algorithms-and-data-structures

Version:

Algorithms and data-structures implemented on JavaScript

47 lines (32 loc) 1.25 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 BubbleSort extends _Sort.default { sort(originalArray) { // Flag that holds info about whether the swap has occur or not. let swapped = false; // Clone original array to prevent its modification. const array = [...originalArray]; for (let i = 1; i < array.length; i += 1) { swapped = false; // Call visiting callback. this.callbacks.visitingCallback(array[i]); for (let j = 0; j < array.length - i; j += 1) { // Call visiting callback. this.callbacks.visitingCallback(array[j]); // Swap elements if they are in wrong order. if (this.comparator.lessThan(array[j + 1], array[j])) { [array[j], array[j + 1]] = [array[j + 1], array[j]]; // Register the swap. swapped = true; } } // If there were no swaps then array is already sorted and there is // no need to proceed. if (!swapped) { return array; } } return array; } } exports.default = BubbleSort;