UNPKG

@kuzanatoliorg/algorithms

Version:

The utils package for react testing library

72 lines (71 loc) 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.timSort = void 0; const utils_1 = require("../utils"); const insertion_sort_1 = require("../insertion-sort"); const getMinrun = (n) => { let r = 0; while (n >= 64) { r |= n & 1; n >>= 1; } return n + r; }; const timSort = (arr, comparator = utils_1.defaultComparator, order = true) => { const minrun = getMinrun(arr.length); if (minrun >= arr.length) { return (0, insertion_sort_1.insertionSort)(arr, comparator, order); } let first = 0; const temp = []; while (first < arr.length) { let last = first + 1; if (comparator(arr[first], arr[last])) { while (last + 1 < arr.length && comparator(arr[last], arr[last + 1])) { last++; } last = Math.max(last, first + minrun); temp.push(arr.slice(first, last)); } else { while (last + 1 < arr.length && !comparator(arr[last], arr[last + 1])) { last++; } last = Math.max(last, first + minrun); temp.push(arr.slice(first, last).reverse()); } first = last; } let sortedArr = (0, insertion_sort_1.insertionSort)(temp[0], comparator, order); for (let ind = 1; ind < temp.length; ind++) { let i = 0, j = 0, k = 0; const ans = []; const next = (0, insertion_sort_1.insertionSort)(temp[ind], comparator, order); while (i < sortedArr.length && j < next.length) { if (order ? comparator(sortedArr[i], next[j]) : comparator(next[j], sortedArr[i])) { ans[k] = sortedArr[i]; i++; } else { ans[k] = next[j]; j++; } k++; } while (i < sortedArr.length) { ans[k] = sortedArr[i]; k++; i++; } while (j < next.length) { ans[k] = next[j]; k++; j++; } sortedArr = ans; } return sortedArr; }; exports.timSort = timSort;