1. Basic Ideas
Assume that the records to be sorted are stored in the array R [1. n. In the initial phase, R [1] is a self-contained ordered zone, and the unordered zone is R [2. n]. From I = 2 until I = n, insert R [I] into the current ordered zone R [1 .. I-1] sequentially to generate an ordered zone containing n records.
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head> <title> sort by direct insertion of javascript </title>
<Meta charset = "UTF-8"/>
</Head>
<Body>
<Script>
Var arr = [];
For (var I = 0; I <20; ++ I)
{
Arr. push (~~ (Math. random () * 20 ));
}
Document. write (arr + "<br/> ");
Array. prototype. insertionSort = function ()
{
Var j;
Var value;
For (var I = 1; I <this. length; I ++)
{
J = I;
Value = this [j];
While (j> 0 & this [J-1]> value)
{
This [j] = this [J-1];
J --;
}
This [j] = value;
}
}
Arr. insertionSort ();
Document. write (arr + "<br/> ");
</Script>
</Body>
</Html>