First, the rules of inserting sorting
1. Starting from 1 increments of 1
2. Need to record the data being sorted
3. Record where the sorted data should be inserted
4. The preceding data (sorted) is moved backward, as long as it is larger than the sorted data, until it is larger or equal to stop comparing (the position of the stop subscript is the position of the sorted data).
5. Insert the sorted data into the corresponding location
Second, the code example
public class Insertsort
{
public static void Main (string[] args)
{
long[] Testarr = new long[]{111, 3, 5, 3456, 33, 2, 899, 1, 5};
Long Templong; Sorted Data Temp Variable
int tempint; Temporary variable for insertion position
for (int i = 1; i < testarr.length;i++)
{
Templong = Testarr[i]; Back up the sorted data
Tempint = i; Record the sorted data location
The preceding data (sorted) is moved backward, as long as it is larger than the sorted data, until it is larger or equal to the stop//stop comparison (the position of the stop subscript is the position of the sorted data).
while (Tempint > 0 && testarr[tempint-1] > Templong)
{
Testarr[tempint] = testarr[tempint-1];
--tempint; Move data position forward
}
Testarr[tempint] = Templong;
}
Print sorted data
for (int i = 1; i < testarr.length;i++)
System.out.println (Testarr[i]);
}
}
Java Insert Sort