improved insertion sort with function style (#41)

pull/46/head
Visrut 2021-01-28 23:54:46 +05:30 committed by GitHub
parent 1d008011a9
commit fa3f0e084f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 11 deletions

View File

@ -1,13 +1,16 @@
let sort = [12,6,3,88,1,4,8]; function insertionSort(array) {
// start with index 1 because only one element is already sorted
for(let i = 0; i<sort.length; i++){ for(let i=1; i<array.length ; i++) {
let key = sort[i]; let key = array[i];
let j = i-1; let j = i - 1;
//comparing keys with other elements // decrement j until array[j] is not less or equal to key
while(key<sort[j] && j>=0){ while(j >= 0 && array[j] > key) {
sort[j+1]=sort[j]; array[j+1] = array[j];
j--; j--;
}
array[j+1] = key;
} }
sort[j+1]=key; return array;
} }
console.log(sort)
console.log(insertionSort([4,5,6,7,8,10,1,2,3,4])) // output : [1,2,3,4,4,5,6,7,8,10]