1.0.3 • Published 1 year ago
@sherstack/algo v1.0.3
@sherstack/algo
Allll the algorithms with additional features
Insertion Sort
Example
import { insertionSort } from '@sherstack/algo';
let arr = [
{ val: 'O', placement: 4 },
{ val: 'H', placement: 0 },
{ val: 'L', placement: 3 },
{ val: 'E', placement: 1 },
{ val: 'L', placement: 2 }
];
const printSwap = async (arr, moveLeft, moveRight) => {
console.log('Swapping ' + arr[moveLeft].val + ' with ' + arr[moveRight].val);
};
const options = {
up: true,
byProperty: 'placement',
doThisEachSwap: printSwap,
doThisEachSwapParams: ['arr', 'swapItem1', 'swapItem2'],
swapFirst: true,
callback: () => {
console.log('Done sorting');
console.log(arr);
}
};
await insertionSort(arr, options);
/*
OUTPUT
-------
Swapping O with H
Swapping O with L
Swapping O with E
Swapping L with E
Swapping O with L
Swapping L with L
Done sorting
[
{ val: 'H', placement: 0 },
{ val: 'E', placement: 1 },
{ val: 'L', placement: 2 },
{ val: 'L', placement: 3 },
{ val: 'O', placement: 4 }
]
*/
Options
insertionSort supports 6 options, all of which are optional. Pass the options
object after the array.
- up - boolean (Ascending order if
true
. Descending order iffalse
. Defaults to true.) - byProperty - string (If the values in the array are objects, sort by this property. By default, the array is sorted by the values themselves.)
- doThisEachSwap - function (This will run after each swap.)
- doThisEachSwapParams - array (Only accept the following values in the array: 'arr', 'i', 'j', 'swapItem1', 'swapItem2')
- swapFirst - boolean (Swap before running doThisEachSwap. Defaults to false.)
- callback - function (Runs after the sort is done)