SHARE
TWEET

Untitled

a guest May 19th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top