【问题标题】:Why is this implementation of merge sort of 100,000,000 number can't be done为什么无法完成对 100,000,000 个数字的合并排序的这种实现
【发布时间】:2022-11-04 03:06:05
【问题描述】:

我正在用 100.000.000 个数字测试合并排序,它挂了。我已经用堆排序完成了它,时间是 65 秒,我也用 10,000,000 个元素进行了合并排序,它仍然做得很好。不知道为什么挂了有人有想法吗?

#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>

using namespace std;
void merge(int a[], int l, int m, int r)
{
    int i, j, k = l;
    int n1 = m - l + 1; // so phan tu cua mang 1
    int n2 = r - m;     // so phan tu cua mang 2
    int *L = new int[n1];
    int *R = new int[n2];

    for (i = 0; i < n1; i++)
        L[i] = a[l + i]; // sao chep cac phan tu cua mang can chia vao cac mang con
    for (j = 0; j < n2; j++)
        R[j] = a[m + j + 1];

    i = 0;
    j = 0;
    while (i < n1 && j < n2)
        if (L[i] < R[j])
            a[k++] = L[i++];
        else
            a[k++] = R[j++];
    while (i < n1)
        a[k++] = L[i++];
    while (j < n2)
        a[k++] = R[j++];
}
void mergeSort(int a[], int l, int r)
{
    if (l < r)
    {
        int m = (l + r) / 2;    // tim phan tu middle de chia
        mergeSort(a, l, m);     // chia
        mergeSort(a, m + 1, r); // chia
        merge(a, l, m, r);      // tron
    }
}
int main()
{

    int size;
    cout << "Nhap so phan tu cua mang sinh ngau nhien: ";
    cin >> size;
    int *arr = new int[size];
    srand(time(0));
    for (int i = 0; i < size; i++)
    {
        arr[i] = rand() % 2000000000;
    }

    mergeSort(arr, 0, size - 1);
    cout << "done!";
    return 0;
}

我觉得这是因为 int *arr= new int[size]

【问题讨论】:

  • 一方面,因为您在merge 函数中泄漏内存,就像筛子泄漏雨水一样。
  • OT:arr[i]= rand() % 2000000000; 你的int 这么大吗? rand() 甚至有那个范围吗?
  • int *L = new int[n1]; --> std::vector&lt;int&gt; L(n1), R(n2); 。此外,如果您想了解如何使用现代 C++ see this link 实现归并排序。
  • 对于尺寸,您不应该使用int,而是使用std::size_t,如果您使用std::vector&lt;int&gt;,您可能还想使用use std::sort(看看这有多快,以及重用测试代码有多容易)
  • 如果您想了解为什么 int 不适合您的 2000000000,请看这里:en.cppreference.com/w/cpp/types/numeric_limits。然后检查代码中 int 的值。 int max_value = std::numeric_limits&lt;int&gt;::max()

标签: c++ sorting memory mergesort allocation


【解决方案1】:

在合并中,删除两个临时数组:

    while (j < n2)              // existing code
        a[k++] = R[j++];
    delete[] R;                 // delete temp arrays
    delete[] L;

在 main 中,删除 arr:

    cout << "done!";            // existing code
    delete[] arr;               // delete arr

我不确定 rand()。我通常使用它来代替:

int rnd32()                     // visual studio rand is only 15 bits
{
static uint32_t r = 0;          // or = time(0)
    r = r*1664525 + 1013904223;
    return (int)r;
}

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 2012-11-07
    • 2021-04-23
    • 2011-07-06
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多