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)