public class lzInsert {
public static void main(String[] args) {
int[] arr = {101, 34, 119, 1, -1, 89};
getInsert(arr);
System.out.println(Arrays.toString(arr));
}
public static void getInsert(int arr[]){
int temp;
for (int i = 1; i < arr.length; i++) {
int index = i - 1;
int val = arr[i];
while (index >= 0 && val < arr[index]){
arr[index + 1] = arr[index];
index --;
}
if(index + 1 != i){
arr[index + 1] = val;
}
错误情况:
val 写成了 arr[i]
debug后看出 arr[index + 1] = arr[index]这行代码把arr[i]的值改变,arr[i]的值不再时val,所以再循环就错误。