The insertion sort is also a classic sort, suitable for arrays that are already basically ordered and have a smaller amount of data. Wrote a Java version of the insert sort yourself. Please refer to the students.
Package leilei.bit.edu.t2; Public classInsertsort { Public Static void Insertsort(int[] a) {intArr_length = A.length;intJ//Current position, section J location to be determined intI//Push forward to compare the position. int value;//Current position, the value of the first J positionSystem. out. Print ("Before sort, the array is:"); Printarr (a);//Start a cycle comparison from the second position for(j =1; J < Arr_length; J + +) {value= A[j]; i = J-1;//If the first position is larger than the current position, move the data in position I while(i>0&& a[i]>value) {a[i+1] = A[i]; i--; }//Find the current position, that is, the value of the J position needs to be inserted in the exact position. a[i+1] =value; } System. out. Print ("After sort, the array is:"); Printarr (a); } Public Static void Printarr(int[] a) { for(intI=0; i<a.length; i++) {System. out. print (A[i] +" "); } System. out. println (); } Public Static void Main(string[] args) {int[] A = {1,5,4,3,8,9,7,6,2}; Insertsort (a); }}
Results of the operation:
arrayis:154389762Afterarrayis:123456789
Specific ideas, in fact the code in the comments have been explained very clearly. Let's make up a picture when you are free. Hey
Insert Sort Java implementation