Direct Insert Sort

Source: Internet
Author: User

The idea of direct insertion: each time the records to be sorted are inserted into the set of records in front of them by keyword, until the end!


Give a simple example:

The array to be sorted is: [2] 5 9 8 6 1

First time: [2 5] 9 8 6 1

Second time: [2 5 9] 8 6 1

Third time: [2 5 8 9] 6 1

Fourth time: [2 5 6 8 9] 1

Fifth time: [1 2 5 6 8 9]//End


Core code:

for (int i=2,j;i<=numbers.length-1;i++) {numbers[0]=numbers[i];j=i-1;while (Numbers[0]<numbers[j]) {numbers[j    +1]=NUMBERS[J]; j--;} Numbers[j+1]=numbers[0];}

Compare the core code to see the algorithm implementation steps:

    1. Save the record to be sorted to the flag bit number[0]

    2. J=i-1, which is used to insert into a previously lined recordset

    3. The current record corresponding to the J position is moved backward when the termination condition is not satisfied, and J moves forward one

    4. Termination condition: Flag bit or meet condition position


The analysis of the algorithm:

    1. Stability: Stable

    2. Complexity of Time:

      The original data does not need to be moved in the positive order, total comparison: n-1, i.e. O (n)

      The original data is moved frequently in reverse order, total comparison: (n*n+n-2)/2, i.e. O (n*n)

      The original data is unordered, the average number of comparisons for the first trip is: (i+1)/2, Total (n*n+3*n)/4, i.e. O (n*n)

      Therefore, the more the data tends to be in the positive order, the less the number of comparisons and the least number of moves (applicable)

    3. Space complexity: Just waste a unit, numbers[0];

Direct Insert Sort

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.