public class InsertSort { public static void insertSort(int[] array) { for (int i = 1; i < array.length; i++) { int currentValue = array[i];// 当前值 int position = i;// 当前下标 for (int j = i - 1; j >= 0; j--) { //如果当前值比array[j]小,array[j]后移一位,空出j的位置,好让下一次循环的值后移 if (currentValue < array[j]) { array[j + 1] = array[j];//将array[j]值后移 position = position - 1;//下标往前移一位,继续对比 } else { break; } } array[position] = currentValue; } } public static void main(String[] args) { int[] array = { 3, -1, 0, -8, 2, 1 }; System.out.println(Arrays.toString(array)); insertSort(array); System.out.println(Arrays.toString(array)); } }
发表评论(对文章涉及的知识点还有疑问,可以在这里留言,老高看到后会及时回复的。)