Basic algorithm: insert sorting

Source: Internet
Author: User

Today, I started to learn about the algorithm and wrote an insertion Sorting Algorithm in a way that I can understand.

 

Package SortInsert;

Public class SortInsert {

Public static void main (String args []) {
Int sortData [] = {4, 1, 2, 3, 8, 6, 5, 9, 11 };
Sort (sortData );
System. out. println (sortData );
}

Static int I, j, tmp;

Public static void sort (int data []) {
For (I = 1; I <data. length; ++ I ){
Tmp = data [I];
J = I-1;
While (true ){

If (j <0 | data [j] <tmp)
Break;
Data [j + 1] = data [j]; // if this number is greater than the number to be sorted, move one unit backward.
J --;
}
Data [j + 1] = tmp;
}
}
}

 

1. assume that the preceding data [n-1] has been sorted. to sort data [n], first save data [n] to the Temporary Variable tmp for later insertion to the appropriate location.

2. when data [n-1] is greater than data [n], data [n-1] moves a unit backward. to insert the location where data [n-1] is not moved before when data [N-2] is smaller than tmp (the value to be sorted.

3. if data [N-2] is still greater than tmp, data [N-2] moves a unit backward to make the data [n-3] Less Than tmp (the value to be sorted, insert the location of the data [N-2] before it is moved, and so on.

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.