【发布时间】:2014-04-18 21:21:05
【问题描述】:
在我需要实现合并排序来对 500,000 个项目进行排序的类项目中工作。 经过多次尝试,我尝试在网上寻找源代码,并在这里找到了一些:http://www.sanfoundry.com/cpp-program-implement-merge-sort/
我不得不更改代码以使用动态数组(用于大小)。当程序运行合并函数时,我使用正在合并的元素数(或高)创建一个新的动态数组。一旦函数完成对它们的排序并将它们合并到原始数组中,我在新的动态数组上使用 delete[]。这是我得到“检测到堆损坏”错误的地方。
这是代码(文字墙):
//Heap Sort
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
//Function Prototypes
void mergesort(int *a, int low, int high);
void merge(int *a, int low, int high, int mid);
int main()
{
//Start with element 1 of the array
int line_no = 0;
int num;
int array_size = 500000;
int* num_array = new int[array_size];
//Open file for input
fstream in_file("CSCI3380_final_project_dataset.txt", ios::in);
//Test for file opening
if (!in_file)
{
cout << "Cannot open words1.txt for reading" << endl;
exit(-1);
}
//Read file
while(true)
{
//Read one line at a time
in_file >> num;
//Test for eof
if (in_file.eof())
break;
num_array[line_no] = num;
//Increment array position
line_no++;
}
//Close the file
in_file.close();
//Start Time
clock_t time_a = clock();
//Run Sorting Algorithim
mergesort(num_array, 0, array_size-1);
//End Time
clock_t time_b = clock();
//Elapsed Time
if (time_a == ((clock_t)-1) || time_b == ((clock_t)-1))
{
cout << "Unable to calculate elapsed time" << endl;
}
else
{
int total_time_ticks = time_b - time_a;
cout << "Elapsed time: " << total_time_ticks << endl;
}
delete[] num_array;
return 0;
}
void mergesort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
return;
}
void merge(int *a, int low, int high, int mid)
{
//--------------------------Create new array-------------------------------
int* sort_array = new int[high];
//--------------------------New Array Created-----------------------------
int i, j, k;
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
sort_array[k] = a[i];
k++;
i++;
}
else
{
sort_array[k] = a[j];
k++;
j++;
}
}
while (i <= mid)
{
sort_array[k] = a[i];
k++;
i++;
}
while (j <= high)
{
sort_array[k] = a[j];
k++;
j++;
}
for (i = low; i < k; i++)
{
a[i] = sort_array[i];
}
//---------------------------Delete the New Array--------------------
delete[] sort_array;
//--------------------------Oh No! Heap Corruption!------------------
}
【问题讨论】:
-
你喜欢空白! :D
-
C++ 的第一条规则:不要自己管理内存。
-
我认为您正在访问 1 超过您在合并中创建的 sort_array 的末尾。您无法访问 sort_array[high]。
-
"合并排序" - 这应该是自上而下还是自下而上的合并排序?虽然自上而下的归并排序是一种常见的课堂练习,但大多数“现实世界”归并排序都是自下而上的。在任何一种情况下,您都可以一次性分配第二个临时数组,并从一个数组到另一个数组并返回合并步骤,方向取决于自上而下的递归级别或自下而上的迭代。对于自上而下,递归部分需要两个“姐妹”函数,一个以原始数组中的数据结束,另一个以临时数组中的数据结束,每个“姐妹”函数调用另一个。
-
对于自下而上,您将 n 个元素的数组视为大小为 1 的 n 组。您将偶数组和奇数组从一个数组合并到另一个数组,每次完成一次传递时方向交替.完成传递后(将所有元素合并到“其他”数组),然后将大小加倍 (2, 4, ... ) 并交换指针以改变方向。当组大小大于或等于数组大小时进行排序。
标签: c++ mergesort dynamic-memory-allocation delete-operator heap-corruption