Advertisement
Guest User

Untitled

a guest
May 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. function insertionSort(A) {
  2. const len = A.length;
  3.  
  4. for(let i = 0; i < len; i++) {
  5. /* storing current element whose left side is checked for its correct position */
  6. const temp = A[i];
  7. let j = i;
  8.  
  9. /* check whether the adjacent element in left side is greater or less than the current element. */
  10. while(j > 0 && temp < A[j - 1]) {
  11.  
  12. // moving the left side element to one position forward.
  13. A[j] = A[j - 1];
  14. j = j - 1;
  15. }
  16.  
  17. // moving current element to its correct position.
  18. A[j] = temp;
  19. }
  20.  
  21. return A;
  22. }
  23.  
  24. const arr = [5, 9, 2, 3];
  25.  
  26. const sorted = insertionSort(arr);
  27.  
  28. console.log('sorted --->', sorted);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement