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'循環後兩個循環,因爲從陣列的左下方複製可能有不止一個元素,或從陣列的頂部一個以上的元素。只有一個循環會做任何事情。 –