|
| 1 | +/*In insertion sort, we divide the initial unsorted array into two parts; |
| 2 | +* sorted part and unsorted part. Initially the sorted part just has one |
| 3 | +* element (Array of only 1 element is a sorted array). We then pick up |
| 4 | +* element one by one from unsorted part; insert into the sorted part at |
| 5 | +* the correct position and expand sorted part one element at a time. |
| 6 | +*/ |
| 7 | +function insertionSort(unsortedList) { |
| 8 | + var len = unsortedList.length; |
| 9 | + for (var i = 1; i < len; i++) { |
| 10 | + var tmp = unsortedList[i]; //Copy of the current element. |
| 11 | + /*Check through the sorted part and compare with the number in tmp. If large, shift the number*/ |
| 12 | + for (var j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) { |
| 13 | + //Shift the number |
| 14 | + unsortedList[j + 1] = unsortedList[j]; |
| 15 | + } |
| 16 | + //Insert the copied number at the correct position |
| 17 | + //in sorted part. |
| 18 | + unsortedList[j + 1] = tmp; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +var arr = [5, 3, 1, 2, 4, 8, 3, 8]; |
| 23 | +insertionSort(arr); |
| 24 | +console.log(arr); |
0 commit comments