Background
I am doing an insertion sort and I would like it to be as efficient as the algorithm allows.
Code
After much research, this is what I made:
const isFunction = require("lodash.isfunction"); //copy pasta from lodash :D
const insertion = ( array ) => {
if(!Array.isArray(array))
throw new Error("array must be an Array");
if (array.length === 0)
return [];
//shallow copy
const clonedArray = array.slice();
//Optimized iterative version: https://en.wikipedia.org/wiki/Insertion_sort
let i = 1, j, temp;
while( i < clonedArray.length ){
temp = clonedArray[i];
j = i - 1;
while( j >= 0 && clonedArray[ j ] > temp ){
clonedArray[ j + 1 ] = clonedArray[ j ];
j = j - 1;
}
clonedArray[ j + 1 ] = temp;
i = i + 1;
}
return clonedArray;
};
module.exports = insertion;
Questions
I tested the code and I know it works. But I wonder if the algorithm available in wikipedia is the best insertion sort algorithm.
Having in mind I wish this function's API to be pure ( I don't want to change the original array, I want to return a new one), I have the following questions:
- Is there a better way to code insertion sort?
- What improvements can be made to this code?
array.slice. BTW if copy an array use spread operatorcloneArray = [...array];For Javascript and because you are making a copy you can use acloneArray = new Float64Array(array.length);which will improve indexing time \$\endgroup\$