Sort and principle of insertion

Source: Internet
Author: User

The basic idea of sorting is that after I-1 processing, L [1 .. I-1] has arranged the order. I-repeat only inserts L [I] into the proper position of L [1 .. I-1] so that L [1 .. I] is a sorted sequence. To achieve this goal, we can use the sequential comparison method. First compare L [I] and L [I-1], if L [I-1] ≤ L [I] Then [1 .. i] the order has been sorted, the I-th processing is over; otherwise, the position of switching L [I] and L [I-1] continues to compare L [I-1] and L [I-2], until a position j (1 ≤ j ≤ i-1) is found so that L [j] ≤ L [j + 1. In short, insertion sorting means that each step inserts a data to be sorted to an appropriate position in the sorted data according to its size until all data is inserted. The insert sorting method is divided into two types: Direct insertion sorting and semi-insertion sorting. Here we only introduce direct insertion sorting, and semi-insertion sorting is left in the "Search" content. Figure 1 demonstrates the process of directly inserting and sorting the four elements. Three inserts are required: (a), (B), and (c. Code: nt a [] = }; int temp = 0; for (int I = 1; I <. length; I ++) {int j = I-1; temp = a [I]; for (; j> = 0 & temp <a [j]; j --) {a [j + 1] = a [j]; // move the value greater than temp to a unit.} a [j + 1] = temp ;} for (int I = 0; I <. length; I ++) System. out. println (a [I]);}

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.