Insert Sort
The insertion sort is implemented in this way:
First, create an empty list to hold sorted ordered sequences (which we call "ordered lists").
Remove a number from the original series and insert it into an ordered list so that it remains in an orderly state.
Repeat step 2nd until the original sequence is empty.
The average time complexity of the insertion sort is square, but it is not efficient but easy to implement. It draws on the idea of "gradually enlarging results", which increases the length of an ordered list until its length equals the length of the original list.
(Quote from Baidu Encyclopedia)
JavaScript code
Copy Code code as follows:
<script type= "Text/javascript" >
var org = [5, 4, 3, 2, 1, 6, 7, 9, 8, 10];
var Temparr = new Array ();
for (var i = 0; i < org.length i++) {
if (i = = 0) {
Temparr[0] = org[0];///Put the first element in the new sequence
} else {
for (var j = 0; J < Temparr.length; J + +) {
if (Org[i] > Temparr[j]) {
//if the last element of the new sequence, insert
if (j = = temparr.length-1) {
Temparr[j + 1] = Org[i];
break;
} else {//if not the last element, move backward
continue;
}
Else {
//move new sequence, then insert
for (var k = temparr.length-1 k >= J; k--) {
Temparr[k + 1] = Te MPARR[K];
}
Temparr[j] = org[i];
break;
}
}
}
}
Alert (Temparr);
</script>