Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // different attempts at insertionSort
- const insert = (sortedItems, itemToInsert) => {
- if (!sortedItems.length) return sortedItems.concat(itemToInsert);
- for (const [ i, sortedItem ] of sortedItems.entries()) {
- if (itemToInsert <= sortedItem) {
- return sortedItems.slice(0, i).concat(itemToInsert).concat(...sortedItems.slice(i));
- }
- }
- return sortedItems.concat(itemToInsert);
- }
- const insertionSort = items => items.reduce((sortedItems, item) => insert(sortedItems, item) , []);
- const sort = nums =>
- !nums.length
- ? []
- : insert(nums[0], sort(nums.slice(1)))
- const insert = (numToInsert, sortedNums) =>
- !sortedNums.length
- ? [ numToInsert ]
- : (numToInsert <= sortedNums[0])
- ? [ numToInsert, ...sortedNums ]
- : [ sortedNums[0], ...insert(numToInsert, sortedNums.slice(1)) ]
- const getSortedNums = nums => nums.reduce((sortedNums, num) => insert(num, sortedNums), [])
- const nums = [ 6, 23, 5, 100, 7 ];
- console.log(insertionSort(nums));
- console.log(sort(nums));
- console.log(getSortedNums(nums));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement