1. Basic idea
Assume that the records to be sorted are stored in the array R[1..n]. Initially, R[1] forms an ordered area, and the unordered area is R[2..n]. From i=2 until i=n, R[i] is inserted into the current ordered area R[1..i-1] in sequence, generating an ordered area containing n records.
javascript direct insertion sorting
< body>
<script> <br>var arr = []; <br>for(var i=0;i<20; i) <BR>{ <BR>arr.push(~~(Math. random()*20)); <BR>} <BR>document.write(arr "<br/>"); <br>Array.prototype.insertionSort = function() <br>{ <br>var j; <br>var value; <br>for(var i=1;i<this.length;i ) <BR>{ <BR>j=i; <BR>value = this[j]; <BR> while(j>0 && this[j-1]>value) <br>{ <br>this[j] = this[j-1]; <br>j--; <br>} <br>this [j] = value; <br>} <br>} <br>arr.insertionSort(); <br>document.write(arr "<br/>"); <br></script>