Java algorithm Start Insert sort instance _java

Source: Internet
Author: User

During the Chinese New Year, I read the introduction of the algorithm in this book, I feel a good benefit. Here also based on the algorithm in the introduction of the algorithm used in Java implementation.
In the first chapter we start with the sort, and the principle of the insertion sort is simple, just like when we play poker. If the hand is smaller than the one before him, continue to compare forward, knowing that this card is more than the card in front of him can be inserted behind him. Of course, in the computer we also need to be compared to the card to move backward one can.
Here the algorithm is given directly, I believe many programmers feel that some programs are better than our natural language to understand.

Copy Code code as follows:

public class Sort {
public void sort (int[] s) {
if (s.length<1) {
return;
}
for (int i = 1; i < s.length; i++) {
int key =s[i];
int j=i-1;
while (J>=0&&s[j]>key) {
S[J+1]=S[J];
j--;
}
S[j+1]=key;
}
}
public static void Main (string[] args) {
Sort s=new sort ();
Int[] St =new int[]{7,5,3,4,2,1};
S.sort (ST);
for (int i = 0; i < st.length; i++) {
System.out.println (St[i]);
}
}
}

His time complexity is O (n*n), is in-situ (at all times requires a constant number of two of elements space to store data and merge sort is not in-situ)

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.