我正在尝试实现Merge-sort,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
void merge_inplace (int *elem , int *axu, int lo, int mid, int hi)
{
int i =lo;
int j= mid +1;
for (int k=lo;k<hi; k++)
{
axu[k]=elem[k];
}
for(int k=lo; k<hi;k++)
{
if(i> mid)
elem[k]=axu[i++];
else if(j> hi)
elem[k]=axu[j++];
else if (axu[i]<axu[j])
elem[k]= axu[i++];
else elem[k]= axu[j++];
}
}
void mergesort(int *elem ,int *axu, int lo,int hi)
{
if(hi<=lo) return;
int mid = lo + (hi-lo)/2;
mergesort(elem,axu, lo, mid);
mergesort(elem,axu, mid+1,hi);
merge_inplace(elem,axu,lo, mid, hi );
}
int main()
{
ifstream in_file ;
ofstream out_file;
int size =0;
int element;
int* elem;
in_file.open("in_file.txt");
if (!in_file )perror ("Error openning file");
in_file >> size;
elem = new int[size];
for (int i=0; i<size;i++)
{
in_file >> elem[i];
}
int * axu = new int [size];
mergesort (elem,axu,0,size-1);
out_file.open("out_file.txt");
if (out_file.fail())
{
printf( "Error opening file for output.\n");
return 0;
}
for (int i=0; i < size; i++)
{
out_file << elem[i];
}
out_file.close();
return 0;
}
“out_file.txt”中程序的输出如下:
调试后我发现当合并函数返回时,元素数组会破坏并使值错误-842150451-842150451-842150451-842150451-842150451-842150451-33686019-1414812757-84215045110
我的输入文件包含(每行一个整数):
10 9 7 5 1 8 3 6 4 2 10
答案 0 :(得分:0)
合并排序和错误的一些错误将辅助初始化转移到合并排序功能
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
void merge_inplace (int *elem , int *axu, int lo, int mid, int hi)
{
int i =lo;
int j= mid +1;
for (int k=0;k<=hi; k++) // <------------- transfer initialization into the merge
{
axu[k]=elem[k];
}
for(int k=lo; k<=hi;k++)
{
if(i> mid)
elem[k]=axu[j++]; // <----------------- i<--->j
else if(j> hi)
elem[k]=axu[i++]; // <------------------ i<--->j
else if (axu[i]<axu[j])
elem[k]= axu[i++];
else elem[k]= axu[j++];
}
}
void mergesort_book(int *elem ,int *axu, int lo,int hi)
{
if(hi<=lo) return;
int mid = lo + (hi-lo)/2;
mergesort_book(elem,axu, lo, mid);
mergesort_book(elem,axu, mid+1,hi);
merge_inplace(elem,axu,lo, mid, hi );
}
//static void merge(vector <int> elements, )
int main()
{
ifstream in_file ;
ofstream out_file;
int size =0;
int element;
int* elem;
in_file.open("in_file.txt");
if (!in_file )perror ("Error openning file");
in_file >> size;
elem = new int[size];
for (int i=0; i<size;i++)
{
in_file >> elem[i];
}
int * axu = new int [size];
mergesort_book (elem,axu,0,size-1);
out_file.open("out_file.txt");
if (out_file.fail())
{
printf( "Error opening file for output.\n");
return 0;
}
for (int i=0 ; i < size; i++)
{
//out_file << elem[i];
printf("%d\n", elem[i]);
}
out_file.close();
return 0;
}