尝试实现合并排序,但排序输出不正确......
输入:2 8 6 1 10 15 3 12 11 输出为:12 11 15 3 12 11 15 3 8
不确定错误在哪里......
非常感谢任何帮助。感谢
template<class T>
void merge(T data[], int left, int right, T temp[])
{
int mid = (left+right)/2;
int l = left, r= mid+1, t=0;
while(l <= mid && r <= right)
{
if(data[l] < data[r])
temp[t++] = data[l++];
else
temp[t++] = data[r++];
}
while(l <= mid)
temp[t++] = data[l++];
while(r <= right)
temp[t++] = data[r++];
//copy it back
for(int i=0; i<(right-left+1); i++)
data[i] = temp[i];
}
template<class T>
void merge_helper(T data[], int first, int last, T temp[])
{
if(first < last)
{
int mid = (first+last)/2;
merge_helper(data, first, mid, temp);
merge_helper(data, mid+1, last, temp);
merge(data, first, last, temp);
}
}
// merge sort
template<class T>
void mergesort(T data[], int size)
{
T *temp = (T*)malloc(sizeof(T)*size);
merge_helper(data, 0, size-1, temp);
}
答案 0 :(得分:3)
//copy it back
for(int i=0; i<(right-left+1); i++)
data[i] = temp[i];
当你将它复制回原始数组时,这里可能出现问题,你总是从零开始,你必须将它从左边元素复制回到右边元素。
试试这个
for(int i = left,k=0; i<=right;i++,k++)
data[i] = temp[k];