fork download
  1. // your code goes here
  2.  
  3. function insertionSort(arr, n) {
  4. for(let i=1;i<n;i++){ // n-1
  5. let key_element = arr[i];
  6.  
  7. // move the larger elements than arr[i] occuring before i one place ahead
  8. // place arr[i] at the vacant position created
  9. let j = i-1; // assuming that j+1 is the vacant position of arr[i]
  10. while(j>=0 && arr[j]>key_element) {
  11. arr[j+1] = arr[j];
  12. j--;
  13. }
  14. // j+1 is the correct position of arr[i]
  15. arr[j+1] = key_element;
  16. }
  17. return arr;
  18. }
  19.  
  20. console.log(insertionSort([1, 3, 4, 5, 2], 5))
Success #stdin #stdout 0.03s 16660KB
stdin
Standard input is empty
stdout
1,2,3,4,5