[英]Runtime error of C++ implementation of merge sort
So I was working on the problems on Leetcode, 912. This is an as simple as it can be problem-- sort an array in ascending order. 因此,我正在研究Leetcode 912上的问题。这是一个简单的问题,即以升序对数组进行排序。 I am just doing it to go over all the sorting algorithms.
我只是要遍历所有排序算法。 However, when it come to merge sort, I wrote this algorithm and it shows a run time error as shown below.
但是,在进行合并排序时,我编写了此算法,它显示了运行时错误,如下所示。 Some simple test cases with 6 or 10 integers in it passed.
通过了一些简单的测试用例,其中包含6或10个整数。 but an run time error occurs when it comes to a much longer test case.
但是涉及到更长的测试用例时,会发生运行时错误。 Any one have an idea of what part of my code might cause this?
任何人都知道我的代码的哪一部分可能导致这种情况? Many thanks in advance!
提前谢谢了!
void mergesort(vector <int> &nums) {
int length=nums.size();
if (length<2)
{
return ;
}
int mid= length/2;
vector <int> left;
vector <int> right;
for (int x=0;x<mid;x++)
{
left.push_back(nums[x]);
}
for (int y=0;y<length-mid;y++)
{
right.push_back(nums[y+mid]);
}
mergesort(left);
mergesort(right);
merge(left,right,nums);
}
void merge(vector <int>& left,vector <int>& right,vector <int>& nums){
int i,j,count {0};
int l1=left.size();
int l2=right.size();
while (i<l1&&j<l2)
{
if (left[i]<right[j])
{
nums[count]=left[i];
count++;
i++;
}
else
{
nums[count]=right[j];
count++;
j++;
}
}
while (i<l1)
{
nums[count]=left[i];
count++;
i++;
}
while (j<l2)
{
nums[count]=right[j];
count++;
j++;
}
}
vector<int> sortArray(vector<int>& nums){
mergesort(nums);
return nums;
}
I passed test case like :[5,2,3,1] but for a much much longer vector input: I got run time error message: AddressSanitizer: SEGV on unknown address 0x61eff7f80674 (pc 0x000000418d91 bp 0x7fff0f0847c0 sp 0x7fff0f0845a0 T0) 我通过了像:[5,2,3,1]这样的测试用例,但是使用了更长的向量输入:我收到了运行时错误消息:AddressSanitizer:SEGV在未知地址0x61eff7f80674(pc 0x000000418d91 bp 0x7fff0f0847c0 sp 0x7fff0f0845a0 T0)
You do not initialize either i
or j
: 您不初始化
i
或j
:
int i,j,count {0};
This will only initialize count
to 0
. 这只会将
count
初始化为0
。 Turn up or actually read your compiler warnings as it will tell you this. 打开或实际阅读您的编译器警告,因为它会告诉您这一点。
Change this to: 更改为:
int i{0};
int j{0};
int count{0};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.