0
今天在我的CS类中,我们了解了更高效的种类,特别是合并和快速排序。我正在尝试编写合并排序,但我的代码遇到问题。我似乎在这里得到了段错误,并且我不确定我做错了什么。任何人都可以发现我做错了什么,或者可能有多种事情我做错了。我愿意学习,所以请随时提出任何改进建议。为什么我的合并函数给我一个段错误?
void mergeFunc(Person A[], int low, int mid, int high, Person B[])
{
int i, j, k;
i = low, j = mid + 1, k = low; //i indexes first half, j indexes second, k indexes new array
while(i <= mid && j <= high)
{
if(A[i].firstName < A[j].firstName) //If first half has smaller item, add it to new list
{
B[k] = A[i];
i++;
k++;
}
else //Otherwise i and j are equal or j is smaller, so add it instead
{
B[k] = A[j];
j++;
k++;
}
}
if(i > mid) //If i has gone past its part of the array, add the rest of j to the new array
{
B[k] = A[j];
k++;
}
else //Otherwise add the rest of i
{
B[k] = A[i];
k++;
}
for(k = low; k <= high; k++) //Copy the new array back to A
{
A[k] = B[k];
}
}
正如未来的事情,以帮助你是这样的:通过与GDB的程序步骤,你可以看到什么行吧出现segfaults上。在代码中标记一个断点以跳过不相关的东西,然后逐步通过断点。 http://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.html – Matthew
你怎么称呼它? – zdd
您需要的主要'while'循环后两个循环,因为从阵列的左下方复制可能有不止一个元素,或从阵列的顶部一个以上的元素。只有一个循环会做任何事情。 –