Insert sorting:
Traverse arrays from start to end
Compare the current element with all elements before the current element
If the current element is smaller than the previous one, move the current element forward until all elements before the current element are sorted by size
The Code is as follows:
[Html]
Package com. robert. paixu;
/**
* Insert sorting
* Sorting from small to large
* @ Author Administrator
*/
Public class InsertSortAlgorithm {
Public static void main (String [] args ){
Int [] arrays = {20,100,-,-, 20, 15 };
InsertSort (arrays );
Display (arrays );
}
/**
* Insert sorting
*/
Private static void insertSort (int [] arrays ){
// Cyclically traverse the Array
Int currentIndex = 0;
Int preIndex = 0;
For (int I = 0; I <arrays. length; I ++)
{
/**
* Comparison between the current element and all elements before the current element
* 1. Move the current element forward until all elements before the current element are sorted by size
*/
CurrentIndex = I;
PreIndex = I-1;
While (currentIndex! = 0 & preIndex> = 0 ){
If (arrays [currentIndex] <arrays [preIndex])
{
Swap (arrays, currentIndex, preIndex );
CurrentIndex --;
}
Else
{
Break;
}
PreIndex --;
}
}
}
Private static void swap (int [] arrays, int currentIndex, int preIndex ){
Int temp = arrays [currentIndex];
Arrays [currentIndex] = arrays [preIndex];
Arrays [preIndex] = temp;
}
/**
* Display the value of the sorted Array
* @ Param arrays
*/
Private static void display (int [] arrays ){
For (int I = 0; I <arrays. length; I ++ ){
System. out. print (arrays [I] + "");
}
}
}
In the best case, that is, when the array is already ordered, the time complexity of inserting the sort is O (n)
The more ordered the array, the less work you need to do.
In the worst case, the time complexity of the algorithm in the worst case is O (n ^ 2)