PackageKpp.sort;/*** Currently to be inserted element data[i], if DATA[I]>=DATA[I-1], then the order is normal, i++ processing the next element * if DATA[I]<DATA[I-1], first save data[i] to temp, Find the right place to insert K, the element order from K to i-1 * move to the left * Insert temp into k *
Analysis
The direct insert sort is a stable sort.
When a file is not in the same state, the time it takes to insert the order directly differs greatly.
If the initial state of the file is a positive sequence, then each record to be inserted only need to compare one time to find the appropriate location to insert, the algorithm time complexity of O (n), this is the best case.
If the initial state is reversed, then the first I want to insert records need to compare i+1 times to find a suitable location to insert, so the time complexity of O (N2), which is the worst case.
The average time complexity of the direct insert sort is O (n^2). * @authorKPP*/ Public classInsertsort { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intArray[] = {5,3,2,67,1,8}; Insertsort (array); for(intK:array) {System.out.println (k); } } Private Static intInsertsort (inta[]) { intLen =a.length; for(inti = 1;i < len;i++){ if(A[i] < a[i-1]){ inttemp =A[i]; intJ; //Method 1: Locate the insertion position and move the uniform right//Find insertion Position for(j = I-1;j >=0&&temp < a[j];j--); //Unify Move Right for(intK = i-1;k >= j+1;k--) {a[k+1]=A[k]; } //Insert the correct positionA[J+1] =temp; //Method 2: Compare one, move one /*For (j = i-1;j >=0;j--) {if (temp < a[j]) {a[j+1] = a[j]; }else{break; }} a[j+1] = temp;*/ } } return0; }}
Insert Sort Java Implementation