The insertion sort is a little different from the previous two. The Insert sort has a comparison, a moving action, an insertion sort is divided into the sorted part and the To insert section, the data to be inserted is compared with the ordered part, traversing the ordered part, finding the first place than inserting the data, inserting the data, and then moving the data after the insertion position.
Compare, insert, move data, move or a bit of a hassle
Public classInsertone {/** * @authorChengdu *@paramargs*/ Private int[] array; Public voidSetArray (int[] Array) { This. Array =Array; } Public int[] GetArray () {returnArray; } Public voidInsertonemove (intXintY) {//y > x if(X > Array.Length | | y >array.length) {System.out.println ("Array Out of Bounds"); }Else{ if(Array[x] >Array[y]) { inttemp =Array[x]; ARRAY[X]=Array[y]; for(; y > x + 1; y--) {Array[y]= Array[y-1]; } array[x+1] =temp; } } } Public Static voidMain (string[] args) {//TODO auto-generated Method StubInsertone Insertone =NewInsertone (); int[] Testarray = {1,2,7,4,5,6,3,8}; Insertone.setarray (Testarray); Insertone.insertonemove (2, 6); System.out.println (arrays.tostring (Testarray)); }}
Insert Sort
Public classInsertsort {/** * @authorChengdu *@paramargs*/ PrivateInsertone Insertone; Public voidSetinsertone (Insertone insertone) { This. Insertone =Insertone; } PublicInsertone Getinsertone () {returnInsertone; } Public voidInsertsortmethod (int[] Array) { intPOS; intLenarray =Array.Length; Insertone.setarray (array); for(Pos=1; pos < Lenarray; pos++) {System.out.println ("Number of times---------:" +POS); for(inti=0; I < POS; i++) {Insertone.insertonemove (I, POS); } //output parts that are already sorted for(inti=0; i < pos+1; i++) {System.out.println (array[i]); } } } Public Static voidMain (string[] args) {//TODO auto-generated Method StubInsertone Insertone =NewInsertone (); Insertsort Insertsort=NewInsertsort (); Insertsort.setinsertone (Insertone); int[] Array = {9, 1, 6, 3, 4, 2, 5, 13, 15, 10}; Insertsort.insertsortmethod (array); System.out.println ("---------Order-----------------"); for(Integer i:array) {System.out.println (i); } }}
Run
Count---------: 1
1
9
Count---------: 2
1
6
9
Count---------: 3
1
3
6
9
Count---------: 4
1
3
4
6
9
Count---------: 5
1
2
3
4
6
9
Count---------: 6
1
2
3
4
5
6
9
Count---------: 7
1
2
3
4
5
6
9
13
Count---------: 8
1
2
3
4
5
6
9
13
15
Count---------: 9
1
2
3
4
5
6
9
10
13
15
---------Order-----------------
1
2
3
4
5
6
9
10
13
15
Java Insert Sort