// 插入排序
public static void insertSort(int[] array) {
for(int i=array.length-2;i>=0;i--){
for(int j=i+1;j<array.length;j++){
int tempIndex=i;
int temp = array[i];
if(temp>=array[j]){
array[tempIndex]=array[j];
tempIndex=j;
}
else {
array[tempIndex] = temp;
break;
}
if(j==array.length-1)
array[j]=temp;
}
System.out.println(Arrays.toString(array));
}
}
运行结果及报错内容 :原数组为{9, 2, 4, 7, 5, 3}
按上述方法输出结果为:
[9, 2, 4, 7, 3, 5]
[9, 2, 4, 3, 5, 5]
[9, 2, 3, 5, 5, 5]
[9, 3, 5, 5, 5, 5]
[3, 5, 5, 5, 5, 5]
[3, 5, 5, 5, 5, 5]
我的解答思路和尝试过的方法 :把内循环的两个int赋值移到外循环就能正常排序
// 插入排序
public static void insertSort(int[] array) {
for(int i=array.length-2;i>=0;i--){
int tempIndex=i;
int temp = array[i];
for(int j=i+1;j<array.length;j++){
if(temp>=array[j]){
array[tempIndex]=array[j];
tempIndex=j;
}
else {
array[tempIndex] = temp;
break;
}
if(j==array.length-1)
array[j]=temp;
}
System.out.println(Arrays.toString(array));
}
}
输出结果为:
[9, 2, 4, 7, 3, 5]
[9, 2, 4, 3, 5, 7]
[9, 2, 3, 4, 5, 7]
[9, 2, 3, 4, 5, 7]
[2, 3, 4, 5, 7, 9]
[2, 3, 4, 5, 7, 9]
就好了。很奇怪为什么。