sapitando

mySortFns.js

Apr 23rd, 2022 (edited)
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function mySort1(iterable) {
  2.   let p = 0,
  3.       i = 0,
  4.       arr = [...iterable],
  5.       e = arr.length - 1;
  6.   while (p < e) {
  7.     if (arr[i] > arr[i + 1]) { [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; }
  8.     if (i > 0 && arr[i - 1] > arr[i]) { i--; continue; }
  9.     i = ++p;
  10.   }
  11.   return arr;
  12. }
  13.  
  14.  
  15. function mySort2(arr, p = 0, i = 0, e = arr.length - 1) {
  16.   if (p >= e) { return arr; }
  17.   if (arr[i] > arr[i + 1]) { [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; }
  18.   if (i > 0 && arr[i - 1] > arr[i]) { return mySort2(arr, p, --i, e); }
  19.   return mySort2(arr, ++p, p, e);
  20. }
  21.  
  22.  
  23. const mySort3 = (() => {
  24.   let p = 0,
  25.       i,
  26.       arr,
  27.       e;
  28.   return function innerFn(iterable) {
  29.     if (p === 0) { i = p; e = (arr = [...iterable]).length - 1; }
  30.     if (p >= e) { p = 0; return arr; }
  31.     if (arr[i] > arr[i + 1]) { [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; }
  32.     if (i > 0 && arr[i - 1] > arr[i]) { i--; return innerFn(); }
  33.     i = ++p;
  34.     return innerFn();
  35.   };
  36. })();
  37.  
  38.  
  39. const mySort4 = (function outerFn(arr, p, i, e) {
  40.   return (iterable) => {
  41.     if (p === undefined) { p = i = 0; e = (arr = [...iterable]).length - 1; }
  42.     if (p >= e) { return arr; }
  43.     if (arr[i] > arr[i + 1]) { [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]; }
  44.     if (i > 0 && arr[i - 1] > arr[i]) { return outerFn(arr, p, --i, e)(); }
  45.     return outerFn(arr, ++p, p, e)();
  46.   };
  47. })();
  48.  
  49.  
Add Comment
Please, Sign In to add comment