public static void sort(long[] arr){
int h = 1; // 初始化间隔
// 计算最大间隔
while(h < arr.length / 3){
h = 3 * h + 1;
}
while(h > 0){
long temp = 0;
for(int i = h; i < arr.length; i++){
temp = arr[i]; // temp等于数组第i个元素的值
int j = i;
while(j > h - 1 && arr[j - h] > temp){
arr[j] = arr[j - h];
j-=h;
}
arr[j] = temp;
}
// 下一个h值
h = (h - 1) / 3;
}
}
Question:
while(j > h - 1 && arr[j - h] > temp) This line of code, j > h - 1; I don’t understand why j > 0 will cause an array out of bounds Exception, while j > h - 1 will not.
@Running Like the Wind, can you help me take a look? Thank you~
j > h - 1 && arr[j - h] > temp
Taking these two sentences together, your j>0 cannot guarantee that j - h is greater than or equal to 0.
I also think it may be that j>0 cannot satisfy the situation of j-h>=0. You can make the arr array very large. If it still goes wrong, it must be the reason. But from the code point of view, I think j-h is always greater than or equal to 0. I'll help you debug and analyze it later.