为什么数组没有在javacode下面排序?
当我运行代码时,数组p没有排序。 我弄清楚了
为什么会这样?
import java.util.Arrays; public class Main { public static void main (String[] args){ //creating array p int[] p= new int[] {2,7,8,3,9,1,4,5,6,0 }; //sort p[5] to p[9] Arrays.sort(p, 5, 9); for(int l=0;l<p.length;l++) { System.out.print(p[l]); } } }
输出为:2783914560
你特别要求对p [5]到p [9]的部分进行排序, 不包括上限…所以4个元素已经按顺序排列(1,4,5,6)。
如果你想排序到p [9],你应该打电话
Arrays.sort(p, 5, 10);
从文档 :
toIndex
– 要排序的最后一个元素的索引(不包括)
当然,那仍然不会对整个数组进行排序 – 只是它的最后一部分,所以你最终会得到{2,7,8,3,9,0,1,4,5,6}。 要对整个数组进行排序,只需调用Arrays.sort(p)
。
请注意,使用包含下限和独占上限指定范围的模式在计算中非常常见,您应该习惯它。 另一个常见的例子是String.substring
:
String text = "0123456789"; String substring = text.substring(0, 5); // 01234
因为您没有对整个数组进行排序。 在这一行:
Arrays.sort(p, 5, 9);
您只是从位置5到9对数组进行排序。使用可以改为使用:
Arrays.sort(p, 0, p.length);
通过这种方式,您可以确保从第一个位置(索引零)到最后一个位置(最后一个参数表示最后一个独占索引)对整个数组进行排序。
但它更容易使用:
Arrays.sort(p);
如上所述,它会自动对整个数组进行排序。
来自Arrays.sort()
的java文档
要排序的范围从索引fromIndex(包括)延伸到index toIndex,exclusive。
我认为您期望在排序中包含index 9
。 在这种情况下,您需要传递p.length (that is 10) instead of 9
。