|
1 | | -function insertionSort(array) { |
2 | | - return array; |
3 | | -} |
| 1 | +const insertionSort = array => { |
| 2 | + for (var outer = 1; outer < array.length; outer++) { |
| 3 | + // take the comparableElement in the array |
| 4 | + for (var inner = 0; inner < outer; inner++) { |
| 5 | + // comparableElement will be compared with complete array and compare till comparableElement index |
| 6 | + if (array[outer] < array[inner]) { |
| 7 | + // comparableElement check with element if it is smaller than any element |
| 8 | + console.log(array); |
| 9 | + var [elem] = array.splice(outer, 1); // comparableElement will be deleted from the location and merge the array again. |
| 10 | + array.splice(inner, 0, elem); // comparableElement will insert before the just bigger element; |
| 11 | + } |
| 12 | + } |
| 13 | + } |
| 14 | + return array; // return sorted array |
| 15 | +}; |
4 | 16 |
|
5 | 17 | const numbers = [8, 5, 6, 9, 3, 1, 4, 2, 7, 10];
|
6 | | -insertionSort(numbers); |
| 18 | +const sortedNumber = insertionSort(numbers); |
| 19 | +console.log(sortedNumber); |
0 commit comments