hca*_*ulf 8 java arrays sorting
我想int[] array在Java中进行排序,但是将排序后的数组存储为新数组而不是覆盖它.
最明显的方法是创建数组的副本,然后对新数组进行排序,如下所示:
int[] a2 = new int[a.length];
for (int i = 0; i < this.length; i++) {
a2[i] = a[i];
}
Arrays.sort(a2);
Run Code Online (Sandbox Code Playgroud)
但是,有更快的方法吗?我们可以在"同时"排序,因为我们将旧数组的元素复制到新数组中吗?
aio*_*obe 15
你可以用
int[] a2 = IntStream.of(a).sorted().toArray();
Run Code Online (Sandbox Code Playgroud)
但我怀疑它比它更快
int[] a2 = a.clone();
Arrays.sort(a2);
Run Code Online (Sandbox Code Playgroud)
无论它具有相同的复杂性,因此不要期望超过恒定因子加速.