为什么数组没有在javacode下面排序? [英] why array is not sorted in below javacode?
问题描述
当我运行代码时,数组p没有排序。我无法弄清楚
when i run the code ,array p is not sorted. I cant figure out
为什么会发生这种情况?
why is this happening?
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
output is:2783914560
推荐答案
您特别要求对p [5]到p [9] 独占的部分进行排序的上限...所以4个元素,已经按顺序排列(1,4,5,6)。
You're specifically asking to sort the portion from p[5] to p[9] exclusive of the upper bound... so 4 elements, which are already in order (1, 4, 5, 6).
如果你想排序要p [9] 包含,你应该致电
If you want to sort to p[9] inclusive, you should call
Arrays.sort(p, 5, 10);
来自文档:
toIndex
- 要排序的最后一个元素的索引
toIndex
- the index of the last element, exclusive, to be sorted
当然,仍然不会对整个数组进行排序 - 只是它的最后一部分,所以你最终会得到{2,7,8,3,9,0,1 ,4,5,6}。要对整个数组进行排序,只需调用 Arrays.sort(p)
。
Of course, that still won't sort the whole array - just the last part of it, so you'd end up with { 2, 7, 8, 3, 9, 0, 1, 4, 5, 6 }. To sort the whole array, just call Arrays.sort(p)
.
请注意指定a的模式使用包含下限和独占上限的范围在计算中是常见的非常,你应该习惯它。另一个常见的例子是 String.substring
:
Note that the pattern of specifying a range using an inclusive lower bound and an exclusive upper bound is very common in computing, and you should get used to it. Another common example is String.substring
:
String text = "0123456789";
String substring = text.substring(0, 5); // 01234
这篇关于为什么数组没有在javacode下面排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!