02_ Sort _ Insert Sort

Source: Internet
Author: User

Basic principle

Direct Insertion Method idea:1. In raw data, the first data is used as a sorted data series2. Get the next element from the array, scan it from the back forward in the sorted element, and determine the size of the element and the arranged3. If the element of the sort sequence is greater than the new element, move the element to the next position4. Repeat step three until you find that the sorted element is less than or equal to the position of the line element5. Insert a new element into the location6. Repeat steps 2~5 until data processing is complete

For example

Array to sort


Sorting process

First trip Insert 38: "65,97,76,13,27,49,"

Second trip Insert 65: "38,65,97,76,13,27,49"

Third trip Insert 97: "38,65,97, 76,13,27,49"

Four times Insert 76: "38,65,76,97,13,27,49"

Five times Insert 13: "13,38,65,76,97, 27,49"

Six times Insertion 27: "13,27,38,65,76,97,49"

Seventh trip Insert 49: "13,27,38,49,65,76,97"

"Code Implementation"

 PackageCom.sort; Public classTestinsertsort { Public Static int[] Insertsort (int[] a) {        intLength=a.length; inti,j,tmp;  for(i=1;i<length;i++) {tmp=a[i];//Take out an unsorted data             for(j=i-1;j>=0&&a[j]>tmp;j--) {//find a location in a sort sequenceA[J+1]=A[J];//data moves backwards without worrying about being overwritten, because TMP saves the first overwritten data} a[j+1]=tmp;//Insert the data because the for loop above is executed at the end of the j--, so the value is assigned a[j+1]        }        returnA; }     Public Static voidMain (string[] args) {inta[]={2,9,0,8,7,1,5,4,3,6}; A=Insertsort (a);  for(inti=0;i<a.length;i++) {System.out.print (A[i]+" "); }    }}

02_ Sort _ 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.