We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
public static void sort(Comparable[] arr) { int n = arr.length; // 注意下标从1开始,不停往前比较,下标为0的元素默认有效 for (int i = 1; i < n; ++i) { // 先把起始位置的元素暂存 Comparable tmp = arr[i]; // 从位置i开始,从前挨个比较(前面已经是有序地了,这个是前提),一直比较到前面的某个元素比自己小就停下 for (int j = i; j > 0; j--) { if (tmp.compareTo(arr[j - 1]) < 0) { // 起始位置元素比前面的小,就把前面的值附到后面来元素上 arr[j] = arr[j - 1]; } else { // 一直到j前面的元素j-1小于tmp了,说明升序排列完成,把之前存的起始位置元素tmp插入到此处即可 arr[j] = tmp; break; } } }
当j=0时,不会进入for循环。arr[j] = tmp;应该写在内部循环的外面。
public static void sort(Comparable[] arr) { int n = arr.length; // 注意下标从1开始,不停往前比较,下标为0的元素默认有效 for (int i = 1; i < n; ++i) { // 先把起始位置的元素暂存 Comparable tmp = arr[i]; int j = i; // 从位置i开始,从前挨个比较(前面已经是有序地了,这个是前提),一直比较到前面的某个元素比自己小就停下 for (; j > 0; j--) { if (tmp.compareTo(arr[j - 1]) < 0) { // 起始位置元素比前面的小,就把前面的值附到后面来元素上 arr[j] = arr[j - 1]; } else { // 一直到j前面的元素j-1小于tmp了,说明升序排列完成,把之前存的起始位置元素tmp插入到此处即可 break; } } arr[j] = tmp; } }
The text was updated successfully, but these errors were encountered:
我看了下,j的初始值是i,i的取值范围是1~n,j取不到0地
Sorry, something went wrong.
举个例子:8 5 4 5 0 9,执行第一次循环,j = 1,结果:8 8 4 5 0 9;执行j--后,j = 0;不会进入内循环了,arr[j] = tmp;就没有执行了
No branches or pull requests
The text was updated successfully, but these errors were encountered: