const insertSort = (arr) => { for (let i=1;i < arr.length;i++) { insertToRightPosition(arr, i); } } const insertToRightPosition = (arr, i) => { let current = arr[i]; let preIndex = i - 1; for (;preIndex >= 0 && arr[preIndex] > current; preIndex--) { arr[preIndex+1] = arr[preIndex]; } arr[preIndex +1] = current; } let arr = [3,4,6,5,2]; insertSort(arr); console.log(arr);