【问题标题】:10,000,000 Integer Array Insertion Sort in JavaJava中的10,000,000个整数数组插入排序
【发布时间】:2019-03-12 17:41:59
【问题描述】:

因此,我已将插入排序代码正确地编写到它将成功创建 1,000 到 9,999 之间的 10、1,000、100,000 和 1,000,000 个整数的数组,并很好地完成了插入排序算法。但是,当我尝试 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;
    }
}

【问题讨论】:

  • j &gt;= 0替换j &gt; 0
  • 我猜5个小时还不够
  • 这可能只是因为100万和1000万之间的显着差异。您可以多快地简单地遍历 100 万个元素与 1000 万个元素的数组(无 while 循环)?
  • 不要忘记你最坏的情况是O(n^2),这意味着在这种情况下10^14。你能想象这个数字吗?
  • 每次将数组扩大 10 倍时,您必须允许 100 倍的时间。我的猜测是你没有等待足够长的时间。

标签: java arrays sorting insertion


【解决方案1】:

有人对这里可能出现的问题有任何想法吗?

当您将数组扩大 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 缓存,而是更慢的主内存。

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多