gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:15:56 27 4
gpt4 key购买 nike

所以我已经正确地编写了插入排序代码,它可以成功地创建 10、1,000、100,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;
}
}

最佳答案

Anybody have any ideas of what the issue may be here?

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

Is the executer having issues comprehending that many integers or what could the issue stem from?

不,极限是 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 缓存,而是更慢的主内存。

关于java - Java 中的 10,000,000 整数数组插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52695708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com