Learning javascript to implement code insertion sorting

Source: Internet
Author: User

Insert sort
Insert sorting is implemented as follows:
First, create an empty list to save the ordered series (called "ordered List ").
Extract a number from the original sequence and insert it into the "ordered list" to keep it in order.
Repeat Step 2 until the original number column is empty.
The average time complexity of insertion sorting is in the square level, which is inefficient but easy to implement. With the idea of "gradually expanding the results", it gradually increases the length of the ordered list until its length is equal to the length of the original list.
(From Baidu encyclopedia)
Javascript code
Copy codeThe Code is 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]; // place the first element in the new sequence
} Else {
For (var j = 0; j <tempArr. length; j ++ ){
If (org [I]> tempArr [j]) {
// If it is the last element of the new sequence, insert
If (j = tempArr. length-1 ){
TempArr [j + 1] = org [I];
Break;
} Else {// if it is not the last element, move it back
Continue;
}
} Else {
// Move the new sequence and insert it
For (var k = tempArr. length-1; k> = j; k --){
TempArr [k + 1] = tempArr [k];
}
TempArr [j] = org [I];
Break;
}
}
}
}
Alert (tempArr );
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.