Insert SortSuppose we enter "5,1,4,2,3" We start with the second number, the number is 1, and our task is to see if 1 has the correct position, we are comparing the numbers to the left of this number, so we compare 1 and 5, 1:5 is small, so we exchange 1 and 5, the original arrangement becomes "1,5,4,2,3" Next, let's see if the 3rd number is in the right position. This number is 4, its left number is 5, 4:5 is small, so we will be 4 and 5 exchange, arranged into a "1,4,5,2,3" we must continue to see 4 in the right position, 4 on the left is 1, 1:4 is small, 4 will remain motionless. Look at the fourth number, this number is 2, we will 2 and its left side of the number than 2, so the 21 to the left, moving to 2 left is 1, this time the sort becomes "1,2,4,5,3" Finally, we check the fifth number, this number is 3,3 must move to the left, Moving to the left of 3 is up to 2, so our arrangement becomes the "1,2,3,4,5" sort so it's done. The so-called insertion sorting method, is to check the number I, if the number on its left is larger than it, to exchange, this action continues until the number of the left of the number is smaller than it, it can be stopped. Insert Sort method The main loop has two variables: I and J, each time the loop is executed, the number I will be placed in the appropriate position on the left. Code implementation:
PackageCom.zc.manythread;/*** Insert Sort *@authoreven my yes **/ Public classInsertionsort { Public Static voidInsertion_sort (int[] data) {// for(inti = 1; i < data.length; i++) { if(Data[i-1] >Data[i]) { inttemp =Data[i]; intj =i; while(J > 0 && data[j-1] > Temp) {Data[j] = Data[j-1]; J--; } Data[j]=temp; } } } Public Static voidMain (string[] args) {int[] data = {6, 2, 4, 1, 5, 9 }; Insertion_sort (data); for(inti = 0; i < data.length; i++) {System.out.print (Data[i]+ "\ T"); } }}
Insert Sort Algorithm--java