fork download
  1. // your code goes here
  2.  
  3. function insertionSort(arr, n) {
  4. for(let i=1;i<n;i++){
  5. let key_element = arr[i];
  6. let j = i-1;
  7.  
  8. // Move all the elements in range from 0 to i-1
  9. // one position ahead if they are greater than key_element
  10.  
  11. while(j>=0 && arr[j]>key_element) {
  12. arr[j+1] = arr[j];
  13. j--;
  14. }
  15. arr[j+1] = key_element;
  16. }
  17. return arr;
  18. }
  19.  
  20. // [6, 3, 4, 2, 1]
  21.  
  22. // key_element = 3, i=1
  23. // j=0, arr[j] > key, arr[j+1] = 6
  24. // j=-1, [6, 6, 4, 2, 1]
  25.  
  26.  
  27. console.log(insertionSort([6, 3, 4, 2, 1], 5))
Success #stdin #stdout 0.06s 18320KB
stdin
Standard input is empty
stdout
1,2,3,4,6