improved insertion sort with function style (#41)
parent
1d008011a9
commit
fa3f0e084f
|
@ -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]
|
||||||
|
|
Loading…
Reference in New Issue