Advertisement
CLooker

insertionSort fun

Oct 27th, 2018
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // different attempts at insertionSort
  2.  
  3. const insert = (sortedItems, itemToInsert) => {
  4.   if (!sortedItems.length) return sortedItems.concat(itemToInsert);
  5.   for (const [ i, sortedItem ] of sortedItems.entries()) {
  6.     if (itemToInsert <= sortedItem) {
  7.       return sortedItems.slice(0, i).concat(itemToInsert).concat(...sortedItems.slice(i));
  8.     }
  9.   }
  10.   return sortedItems.concat(itemToInsert);
  11. }
  12.  
  13. const insertionSort = items => items.reduce((sortedItems, item) => insert(sortedItems, item) , []);
  14.  
  15. const sort = nums =>
  16.   !nums.length
  17.     ? []
  18.     : insert(nums[0], sort(nums.slice(1)))
  19.  
  20. const insert = (numToInsert, sortedNums) =>
  21.   !sortedNums.length
  22.     ? [ numToInsert ]
  23.     : (numToInsert <= sortedNums[0])
  24.       ? [ numToInsert, ...sortedNums ]
  25.       : [ sortedNums[0], ...insert(numToInsert, sortedNums.slice(1)) ]
  26.  
  27. const getSortedNums = nums => nums.reduce((sortedNums, num) => insert(num, sortedNums), [])
  28.  
  29. const nums = [ 6, 23, 5, 100, 7 ];
  30.  
  31. console.log(insertionSort(nums));
  32. console.log(sort(nums));
  33. console.log(getSortedNums(nums));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement