ts-sort-heap
Version:
heap sort an array in typescript
62 lines (57 loc) • 1.86 kB
JavaScript
/*!
* (c) 2019-2020 jackieli 西门互联
* https://github.com/jackieli123723/ts-sort-array
* http://issue.lilidong.cn
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.tsSortHeap = {}));
}(this, (function (exports) { 'use strict';
var arrLength;
function maxHeap(input, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
var max = i;
if (left < arrLength && input[left] > input[max]) {
max = left;
}
if (right < arrLength && input[right] > input[max]) {
max = right;
}
if (max != i) {
swap(input, i, max);
maxHeap(input, max);
}
}
function swap(input, indexA, indexB) {
var temp = input[indexA];
input[indexA] = input[indexB];
input[indexB] = temp;
}
function heapSortSync(input) {
arrLength = input.length;
for (var i = Math.floor(arrLength / 2); i >= 0; i -= 1) {
maxHeap(input, i);
}
for (var i = input.length - 1; i > 0; i--) {
swap(input, 0, i);
arrLength--;
maxHeap(input, 0);
}
return input;
}
function heapSort(arr, callback) {
var result = heapSortSync(arr);
callback && typeof callback == 'function' && callback(result);
}
function heapSortAsync(arr) {
var result = heapSortSync(arr);
return Promise.resolve(result);
}
exports.heapSort = heapSort;
exports.heapSortAsync = heapSortAsync;
exports.heapSortSync = heapSortSync;
Object.defineProperty(exports, '__esModule', { value: true });
})));