我正在尝试使用 stl 库进行合并排序算法,但遇到了一些问题。下面是我正在使用的代码
template <typename Item, typename SizeType>
void merge_sort(Item array[], SizeType size){
size_t n1; //Size of the first subarray
size_t n2; //Size of the second subarray
if(size > 1){
//Compute the size of the subarrays
n1 = size/2;
n2 = size - n1;
//create the temp array.
int* n1Temp = new int[n1];
int* n2Temp = new int[n2];
int i;
for(i = 0; i < n1; i++)
n1Temp[i] = array[i];
for(i = 0; i < n2; i++)
n2Temp[i] = array[i + n1];
//recursive calls
merge_sort(n1Temp, n1);//sort from array[0] through array[n1 - 1]
merge_sort(n2Temp, n2);//sort from array[n1] to the end
//Merge the two sorted halves.
vector<int> v(array, array + size);
merge(n1Temp, n1Temp + n1, n2Temp, n2Temp + n2, v.begin());
copy(v.begin(), v.end(), array);//copy the vector back to the array
delete[] n1Temp;
delete[] n2Temp;
}
}
代码排序很好,但问题是它的行为类似于 O(n^2) 算法而不是 O(n \log n),这是由于在每个合并排序调用中创建了向量(我认为)。我尝试删除向量并仅在合并函数中使用数组,如下所示
//Merge the two sorted halves.
int* finalArray = new int[n1 + n2];
merge(n1Temp, n1Temp + n1, n2Temp, n2Temp + n2, begin(finalArray));
array = finalArray;
但这只会给我带来错误。我能做些什么来挽救我的归并排序算法吗?