With the first glance, it may look like this sort algorithm that is better than Bubble Sort but worse than Selection Sort. Surprise enough, Insertion Sort is even a little bit better than Selection Sort.
Any way, we need to know that all these three sort algorithms are not using by most of the programs in our computer because they are not efficient enough. They all need two layers loops to compare and move elements. In the worse scenario, an array with n elements may need n*n times steps to achieve the result. It could be 1 million if n is 1000.
for (var i = 1; i < list.length; i++) {
var select = list[i];
var insPos = i;
for (var j = i - 1; j >= 0; j--) {
if (select < list[j]) {
list[j + 1] = list[j];
insPos = j;
}else{
break;
}
}
list[insPos] = select;
}
没有评论:
发表评论