Sort algorithm-Insert sort (JavaScript)

Source: Internet
Author: User

thought : Each trip inserts a record into the appropriate position for a set of records that have been sequenced, knowing that the records to be sorted are inserted.

functionInsertsort (arr) { for(vari=2;i<=arr.length;i++){        if(Arr[i]<arr[i-1]) {//less than when insertingArr[0]=arr[i];//staging the records to be inserted to the lookoutARR[I]=ARR[I-1];//Arr[i-1] Move back             for(varJ=I-2;ARR[0]&LT;ARR[J];--J) {//looking for the insertion position from the back forwardARR[J+1]=ARR[J];//record-by-move, knowing where to find the insertion position} arr[j+1]=ARR[0];//Insert arr[0] i.e. original arr[i] into the correct position        }    }    returnarr;}

Complexity of Time:

The basic operation for sorting is: compare two keywords and move. Best case: Positive order. Compare 1 times, do not move. Worst case: reverse. Compare I times (i-1 plus Sentinel), move i+1 times (i-1 plus move the insertion to the lookout and remove from the monitor). For the entire sort process: best case, the number of comparisons is n-1, not moving. Worst N^2/2 times, N^2/2 times. So the time complexity is O (n^2).

Complexity of space:

Only one record of the secondary space arr[0] is required, so the spatial complexity is O (1).

Algorithm Features:

1. Stable sorting.

2. Easy and easy to implement.

3. Also applies to chained storage structures.

4. More suitable for the initial record of the basic order of the situation. The initial record is unordered, n is large, the time complexity is high, and it is not applicable.

Sort algorithm-Insert sort (JavaScript)

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.