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.