Guest User

Untitled

a guest
Nov 21st, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. const pancakeSort = arr => {
  2. for (let i=arr.length-1; i>=1; i--) {
  3. // 1. find the index of the largest size in unsorted arr
  4. let maxIndex = 0;
  5. let max = arr[0];
  6. for(let j=1; j<=i; j++) {
  7. if(arr[j] > max) {
  8. max = arr[j];
  9. maxIndex = j;
  10. }
  11. }
  12.  
  13. // 2. if the element is maxIndex, continue
  14. if (maxIndex == i) continue;
  15.  
  16. // 3. otherwise, flip the largest element to index 0
  17. let newSlice;
  18.  
  19. if (maxIndex > 0) {
  20. newSlice = arr.slice(0, maxIndex+1).reverse();
  21. for (let j= 0; j<= maxIndex; j++)
  22. arr[j] = newSlice[j];
  23. }
  24.  
  25. // 4. then flip the largest element to the sorted index
  26. newSlice = arr.slice(0, i+1).reverse();
  27. for (let j=0; j<=i; j++)
  28. arr[j] = newSlice[j];
  29. }
  30. return arr;
  31. }
Add Comment
Please, Sign In to add comment