This is a classic algorithm, many friends on the Internet have written, and some I do not understand, so I myself in accordance with the understanding of the written out,
I think the only thing I write is my own.
Main ideas:
1. Sort the first two numbers of the array by size
2. Compare the third number to the first two numbers and insert the third number in the appropriate position
3. Cycle
In fact, it will be difficult for a novice to turn it into a code.
Me too. I am stupid, no way, only will be detailed step by step write out
Array "3, 5,1,2,8,9"
If there is such an array, according to the above idea, we start with the second number, that is, 5,5 to 3 compared to the second position is 5 to insert the position
"3,5, 1,2,8,9"
Then the 5 comparison, 1:5 is small, so, 5 position and 1 position of the value of the exchange, that is, the value shift.
"3,1, 5,2,8,9"
Go ahead a comparison and shift again
"1, 3,5,2,8,9"
This position is where we want to insert it.
Sequentially, the results are sorted as follows.
"1,2, 3,5,8,9"
The main code is as follows:
public void sort (int a[]) {
int length=a.length; Array length
Int J; The position of the current value is 5 for the initial position
int i; Position in front of J is the position of 3 for the initial point.
int key; The current value for the insertion sort is 5 for the initial
The insertion is traversed from the second position of the array, that is, it is compared to the first value of the array, and the first value is moved backward if it is smaller than the first one.
for (j=1;j<length;j++) {
KEY=A[J]; The first time is to assign a value of 5 to key, and the next
I=j-1; The first time is the 3 corresponding position
A[i] is larger than the current value, A[i] moves back one bit, vacated the position of I, so that the next cycle of the value of the move
while (i>=0 && key < A[i]) {//First time is 5:3 large, no loop execution
A[i+1]=a[i]; Move the a[i] value back
i--; I move forward
}//jump out of the loop (find the middle position to insert or have traversed to 0 subscript)
A[i+1]=key; Insert the current value, that is, 3 of the position of the next position, that is, the position of 5, the final result is that the position of 5 points back to 5, the results have no effect
}
}
The above is only the first step to write the details, the following steps are basically the same, the basic algorithm must be understood to be able to write more complex algorithms.
So everything starts with the basics.
Insertion sorting algorithm of Java algorithm