Learn JavaScript, implement insert sort implement code _javascript skill

Source: Internet
Author: User
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>
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.