今天在我的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];
}
}
答案 0 :(得分:0)
假设数组的所有下半部分都位于数组的上半部分之前。您的代码只将数组上半部分的一个元素复制到B数组中,这实际上是不够的。
void mergeFunc(Person A[], int low, int mid, int high, Person B[])
{
assert(low >= 0 && low <= mid && mid <= high);
int i = low;
int j = mid + 1;
int k = low;
while (i <= mid && j <= high)
{
if (A[i].firstName < A[j].firstName)
B[k++] = A[i++];
else
B[k++] = A[j++];
}
while (j <= high)
B[k++] = A[j++];
while (i <= mid)
B[k++] = A[i++];
for (k = low; k <= high; k++)
A[k] = B[k];
}
这段代码更紧凑,更接近惯用C,因为它更好地利用了增量运算符。