我试图在C ++中实现这个mergeSort函数,但我收效甚微。到目前为止我创建的算法对数组的两半进行了排序,但是,我知道在返回之前我需要一些代码,在后半部分之后需要将数组的两半合并在一起。这是我遇到一些问题的地方,我无法弄清楚如何将两者合并在一起。
int mergeSort(empType A[], int first, int last)
{
int mid = (first + last + 1) / 2; // get midpoint
int comp = 0; // holds # of comparisons
empType tempArray;
// Loop to middle, start at first + 1
for (int i = first + 1; i < mid; i++)
{
// if given score < previous
if (A[i].Score < A[i - 1].Score)
{
// set j = what i is at in original for loop
// loop to first + 1 and decrement
for (int j = i; j > first + 1; j--)
{
// if element's score < previous
if (A[j].Score < A[j - 1].Score)
{
tempArray.ID = A[j].ID; // Put ID into tempArray
tempArray.Score = A[j].Score; // Put Score into tempArray
A[j].ID = A[j - 1].ID; // Move on to next ID element
A[j].Score = A[j - 1].Score; // Move on to next Score element
A[j - 1].ID = tempArray.ID; // Put next ID into tempArray
A[j - 1].Score = tempArray.Score; // Put next Score into tempArray
comp++; // Increase computations
}
}
}
}
// loop from middle to last elements
for (int i = mid; i < last; i++)
{
// if current score < previous
if (A[i].Score < A[i - 1].Score)
{
for (int j = i; j > mid + 1; j--)
{
if (A[j].Score < A[j - 1].Score)
{
tempArray.ID = A[j].ID;
tempArray.Score = A[j].Score;
A[j].ID = A[j - 1].ID;
A[j].Score = A[j - 1].Score;
A[j - 1].ID = tempArray.ID;
A[j - 1].Score = tempArray.Score;
comp++;
}
}
}
}
return comp; // return the number of comparisons
}