UNPKG

dist-javascript-algorithms-and-data-structures

Version:

Algorithms and data-structures implemented on JavaScript

55 lines (39 loc) 1.67 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 QuickSort extends _Sort.default { /** * @param {*[]} originalArray * @return {*[]} */ sort(originalArray) { // Clone original array to prevent it from modification. const array = [...originalArray]; // If array has less than or equal to one elements then it is already sorted. if (array.length <= 1) { return array; } // Init left and right arrays. const leftArray = []; const rightArray = []; // Take the first element of array as a pivot. const pivotElement = array.shift(); const centerArray = [pivotElement]; // Split all array elements between left, center and right arrays. while (array.length) { const currentElement = array.shift(); // Call visiting callback. this.callbacks.visitingCallback(currentElement); if (this.comparator.equal(currentElement, pivotElement)) { centerArray.push(currentElement); } else if (this.comparator.lessThan(currentElement, pivotElement)) { leftArray.push(currentElement); } else { rightArray.push(currentElement); } } // Sort left and right arrays. const leftArraySorted = this.sort(leftArray); const rightArraySorted = this.sort(rightArray); // Let's now join sorted left array with center array and with sorted right array. return leftArraySorted.concat(centerArray, rightArraySorted); } } exports.default = QuickSort;