[英]mergesort c++ implementation out of bound index accessing
I'm implementing the merge sort psuedocode from the CLRS algorithms textbook in c++. 我正在用C ++中的CLRS算法教科书实现合并排序伪代码。 Somewhere in my code I access an element of an array that's not in the bounds of the array. 在我的代码中的某处,我访问不在数组范围内的数组元素。 I'm not sure why this happens (it occurs when the left == size of array -1, middle == left, right == size of array). 我不确定为什么会发生这种情况(它发生在左边==数组-1的大小,中间==左边,右边==数组的大小时)。 I'd really appreciate any help. 我真的很感谢您的帮助。 Here is my implementation. 这是我的实现。
void merge(int array[], int left, int middle, int right) {
int left_size = middle - left + 1; //include middle
int right_size = right - middle;
int *left_array = new int[left_size];
int *right_array = new int[right_size];
for (int i = 0; i < left_size; i++)
left_array[i] = array[left + i];
for (int i = 0; i < right_size; i++)
right_array[i] = array[middle + i + 1];
int i = 0;
int j = 0;
int cur = left;
printArray(left_array, left_size);
printArray(right_array,right_size);
while (i < left_size and j < right_size) {
if (left_array[i] < right_array[j])
array[cur] = left_array[i++];
else
array[cur] = right_array[j++];
cur++;
}
while (i < left_size) {
array[cur] = left_array[i++];
cur++;
}
while (j < right_size) {
array[cur] = right_array[j++];
cur++;
}
delete [] left_array;
delete [] right_array;
}
This is how i call the merge function: 这就是我所谓的合并功能:
void mergeSort(int array[], int length) {
mergeSortHelper(array, 0, length);
}
//left inclusive, right exclusive
void mergeSortHelper(int array[], int left, int right) {
if (left < right) {
int middle = floor((left + right) / 2);
mergeSortHelper(array, left, middle);
mergeSortHelper(array, middle + 1, right);
merge(array, left, middle, right);
}
}
When you start with: 当您开始时:
mergeSortHelper(array, 0, length);
you will cause array[length]
to be used. 您将导致使用array[length]
。 array [length-1]
is the last valid refererence. array [length-1]
是最后一个有效参考。
It might work better if you start with: 如果您从以下内容开始可能会更好:
mergeSortHelper(array, 0, length-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.