Insertion Sort in Javascript
Iterate through elements from second to last, check which is bigger with elements behind and keep replacing until not required.
const insertionSort = (arr) => { // functionlet key, j; // variablesfor(let i=1; i<arr.length; i++) { // iterate from second to lastkey = arr[i]; // value under considereationj = i-1; // previous index to iwhile(j >= 0 && arr[j] > key) { // while j is > -1 and value at j > value at iarr[j+1] = arr[j]; // setting next value to be value of jj = j-1; // reducing j by 1}arr[j+1] = key; // setting value at next to j to be value at i}return arr; // return sorted array}console.log(insertionSort([7,1,9,8,5,2,4,6,3]));
Comments
Post a Comment