First look at the diagram to see how Selection Sort is done.
Finally finished-after understanding its behavior pattern, we can begin to write code to implement the
Import Java.util.arrays;public class Testmain {public static void main (string[] args) {int[] Randarray = new int[] {2, 0, 1, 3, 9, 8, 6, 5, 4, 7};insertionsort (Randarray); System.out.println (arrays.tostring (Randarray));} public static void Insertionsort (int[] intarray) {int size = intarray.length;for (int cur = 1; cur < size; cur++) {int j = Cur;while (J > 0 && intarray[j] < intarray[j-1]) {int temp = intarray[j-1];//swap intarray[j-1] = INTARRAY[J];INTARRAY[J] = temp; j--; After the exchange, move forward, continue to compare}}}}
There is a problem in the middle, that is, if the j> 0 is placed in the back face, even if there is a && symbol, j = 0 will enter the judgment, that is
INTARRAY[J-1], will cause an array out of bounds (Intarray[-1]) exception, so we have to put J > 0 in front.
while (Intarray[j] < intarray[j-1] && J > 0) {int temp = intarray[j-1];//swap intarray[j-1] = Intarray [J];intarray[j] = temp; j--; After the exchange, move forward, continue to compare}
Select Sort method (Selection sort) review--with illustration