Find the I, the a[i] and a[0] to a[i-1] in order to exchange the elements smaller than it, in I from left to right changes, I left are ordered, when I reached the rightmost sorting complete.
Inserting a sort is useful for the following arrays:
- Each element in the array is not far from its final position.
- An ordered large array followed by a decimal group
- The position of only a few elements in the array is incorrect
When the number of inverted is small, the insertion sort is likely to be faster than the other sorting algorithms.
Packagesort20171111;ImportJava.util.*; Public classInsertion { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[]a =New int[20]; intN; Scanner in=NewScanner (system.in); N=In.nextint (); for(inti = 0; I < n; i++) {A[i]=In.nextint (); } //Insert Sort for(inti = 1; I < n; i++) { for(intj = i; J > 0; j--) { if(A[j] < a[j-1]) { inttemp; Temp=A[j]; A[J]= A[j-1]; A[j-1] =temp; } } } for(inti = 0; I < n; i++) {System.out.println (a[i]); } }}
Insert Sort (JAVA)