Java 中的 10,000,000 个整数数组插入排序



所以我正确地编写了插入排序代码,它将成功创建 10、1,000、100,000 和 1,000,000 和 1,000,000 个介于 1,000 和 9,999 之间的整数的数组,并很好地完成插入排序算法。但是,当我尝试执行 10,000,000 个整数的最后一步时,将创建数组,但代码永远不会完全完成。我给了它足够的时间来完成,超过4或5个小时,但无济于事。有人对这里的问题有任何想法吗?执行者在理解这么多整数时是否有问题,或者问题可能源于什么?我已经包含了我编写的插入算法的副本。

public static void insertion(int[] a) {
int n = a.length;
for(int i = 1; i < n; i++) {
int j = i -1;
int temp = a[i];
while(j > 0 && temp < a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
}
有人对

这里的问题有任何想法吗?

当您将数组放大 10 倍时,您必须等待 100 倍的时间,因为这是一种 O(n^2( 算法。

执行者在理解这么多整数时是否有问题,或者问题可能源于什么?

不,限制是 2^31-1,您离限制还有很长的路要走。

运行

interface A {
static void main(String[] a) {
for (int i = 25_000; i <= 10_000_000; i *= 2) {
Random r = new Random();
int[] arr = new int[i];
for (int j = 0; j < i; j++)
arr[j] = r.nextInt();
long start = System.currentTimeMillis();
insertion(arr);
long time = System.currentTimeMillis() - start;
System.out.printf("Insertion sort of %,d elements took %.3f seconds%n",
i, time / 1e3);
}
}
public static void insertion(int[] a) {
int n = a.length;
for (int i = 1; i < n; i++) {
int j = i - 1;
int temp = a[i];
while (j > 0 && temp < a[j]) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
}

指纹

Insertion sort of 25,000 elements took 0.049 seconds
Insertion sort of 50,000 elements took 0.245 seconds
Insertion sort of 100,000 elements took 1.198 seconds
Insertion sort of 200,000 elements took 4.343 seconds
Insertion sort of 400,000 elements took 19.212 seconds
Insertion sort of 800,000 elements took 71.297 seconds

所以我的机器可能需要 4 个小时,但可能需要更长的时间,因为更大的数据集不适合 L3 缓存,而是主内存更慢。

最新更新