First, the basic concept
The basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data, and the time complexity is O (n^2). is a stable sorting method. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (where an array has more space to insert), and the second part contains only that element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence.
Second, Java code implementation
Public classInsertsort { Public Static voidInsersort (int[] Array) { if(array==NULL|| Array.length<2){ return; } for(inti=1;i<array.length;i++) {//The default first element is an ordered queue, and the second element starts with a loop insert intPosition=array[i];//set the second element as the data to be inserted intJ=i-1; while(j>=0&&position<Array[j]) {Array[j+1]=ARRAY[J];//if the number of inserts is less than the J element, move the number of J backwardj--; } array[j+1]=position;//Insert } } Public Static voidMain (String ags[]) {int[] Array={2,6,4,7,3,-1}; Insersort (array); for(inti=0;i<array.length;i++) {System.out.print (Array[i]+" "); } }}
View Code
Third, performance analysis
- Stability
- Space complexity O (1)
- Time complexity O (n2)
- Worst case: Reverse order, need to move n (n-1)/2 elements
- Best case: Positive order, no moving element required
Java Insert Sort