UNPKG

algs4js

Version:

Basic algorithms and data structures implemented with es6

75 lines (66 loc) 2.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Class MergeSort * * Implementation of the Quick Sort algorithm using the * Hoare partition algorithm. */ var MergeSort = function () { function MergeSort() { _classCallCheck(this, MergeSort); } _createClass(MergeSort, null, [{ key: "sort", value: function sort(arr) { this.mergeSort(arr, 0, arr.length - 1); } }, { key: "mergeSort", value: function mergeSort(arr, left, right) { if (left >= right) { return; } var mid = Math.floor(left + (right - left) / 2); this.mergeSort(arr, left, mid); this.mergeSort(arr, mid + 1, right); this.merge(arr, left, mid, right); return; } /* eslint no-param-reassign: 0 */ }, { key: "merge", value: function merge(arr, left, mid, right) { var arrCopy = arr.slice(); var i = left; var j = mid + 1; var k = left; while (i <= mid && j <= right) { if (arrCopy[i] < arrCopy[j]) { arr[k] = arrCopy[i]; i++; } else { arr[k] = arrCopy[j]; j++; } k++; } while (i <= mid) { arr[k] = arrCopy[i]; k++; i++; } while (j <= right) { arr[k] = arrCopy[j]; k++; j++; } } }]); return MergeSort; }(); exports.default = MergeSort;