The direct insertion sort of Java implementation of common algorithm

Source: Internet
Author: User

Direct insertion sorting is the insertion of unsorted data into an appropriate position in the ordered sequence.  The process is as follows: 1, first compare the array of the first two data, and sort, 2, compare the third element with the first two rows of data, and put the third element in the appropriate position, 3, compare the fourth element with the first three ordered data, and put the fourth element into the appropriate position;   4, until the last element into the appropriate position.  If there is initial data: 25 11 45 26 12 78.  1, first compare the size of 25 and 11, 11 small, position interchange, the first round after sorting, the order is: [11, 25, 45, 26, 12, 78].  2, for the third data 45, which is greater than 11, 25, so the position is unchanged, the order is still: [11, 25, 45, 26, 12, 78].  3, for the fourth data 26, which is greater than 11, 25, less than 45, so it is inserted between 25 and 45, the order is: [11, 25, 26, 45, 12, 78].  .......   4. The final order is: [11, 12, 25, 26, 45, 78]. The direct insert sort is stable.   The average time complexity of the direct insert sort is O (N2). The Java code is implemented as follows:
1      Public voidSortint[] arr) {2         inttmp;3          for(inti = 1; i < arr.length; i++) {4             //data to be inserted5TMP =Arr[i];6             intJ;7              for(j = i-1; J >= 0; j--) {8                 //determines whether the value is greater than TMP, or greater than9                 if(Arr[j] >tmp) {TenARR[J+1] =Arr[j]; One}Else{ A                      Break; -                 } -             } theARR[J+1] =tmp; -SYSTEM.OUT.PRINTLN (i + ":" +arrays.tostring (arr)); -         } -}

The direct insertion sort of Java implementation of common algorithm

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.