Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.48 KB | None | 0 0
  1. const insertionSort = (arr) => {
  2. for (let i = 0; i < arr.length; i++) {
  3. let el = arr[i];
  4. let j;
  5. // loop over elements to the left of currentEl
  6. for (j = i - 1; j >= 0 && arr[j] > el; j--) {
  7. // keep inserting current element until it gets to its
  8. // proper place
  9. arr[j + 1] = arr[j];
  10. }
  11. // insert current element at the correct index
  12. arr[j + 1] = el;
  13. }
  14. return arr;
  15. }
  16.  
  17. const foo = [5, 3, 1, 2, 4];
  18.  
  19. insertionSort(foo); // returns [1, 2, 3, 4, 5]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement