看数据结构书,看到归并排序,便手动实现其代码,发现普通的两路归并代码是错误的,,,,不晓得原因是啥子。。。。
下表面的代码是R.Sedgewick提出的一个改进的两路归并算法代码,经测试正确无误。
void Merge(int L1[], int L2[], int first, int mid, int last)
{
for(int i=first; i<=mid; i++)
L2[i] = L1[i];
int k = last;
for(int j=mid+1; j<=last; j++)
// L2[last+mid+1-j] = L1[j];
L2[j] = L1[k--];
int s1 = first;
int s2 = last;
int t = first;
while(t<=last)
{
if(L2[s1] <= L2[s2])
L1[t++] = L2[s1++];
else
L1[t++] = L2[s2--];
}
}
void MergeSort(int L1[], int L2[], int first, int last)
{
if(first>=last)
return;
int mid = (first+last)/2;
MergeSort(L1, L2, first, mid);
MergeSort(L1, L2, mid+1, last);
Merge(L1, L2, first, mid, last);
}
int main()
{
int L1[10] = {6,9,3,0,1,7,2,4,5,6};
int L2[10];
MergeSort(L1, L2, 0, 9);
for(int i=0; i<10; i++)
cout<<L1[i]<<endl;
return 0;
}