UNPKG

algs4js

Version:

Basic algorithms and data structures implemented with es6

72 lines (61 loc) 2.42 kB
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _LogUtil = require('../util/LogUtil'); var _LogUtil2 = _interopRequireDefault(_LogUtil); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Class QuickSort * * Implementation of the Quick Sort algorithm using the * Hoare partition algorithm. */ var QuickSort = function () { function QuickSort() { _classCallCheck(this, QuickSort); } _createClass(QuickSort, null, [{ key: 'sort', value: function sort(arr) { this.quickSort(arr, 0, arr.length - 1); } }, { key: 'quickSort', value: function quickSort(arr, left, right) { var idx = this.partition(arr, left, right); if (right <= left) { return; } this.quickSort(arr, left, idx); this.quickSort(arr, idx + 1, right); } /* eslint no-param-reassign: 0 */ }, { key: 'partition', value: function partition(arr, first, last) { // Protect against overflow by adding delta to first index var pivot = arr[Math.floor(first + (last - first) / 2)]; // Hoare algorithm: start outside bounds for cleaner loop code var left = first - 1; var right = last + 1; while (left < right) { while (arr[++left] < pivot) {} while (arr[--right] > pivot) {} if (left < right) { this.swap(arr, left, right); } } _LogUtil2.default.debug('Before return: left => ' + left + ', right => ' + right); return right; } }, { key: 'swap', value: function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }]); return QuickSort; }(); module.exports = QuickSort;