Iam在C++中執行關於不同排序算法的報告。讓我感到困惑的是,我的mergesort似乎比兩種語言的heapsort都慢。我所看到的是heapsort應該會變慢。Mergesort執行速度很慢
我的mergesort以19.8毫秒的速度排序一個大小爲100 000的未排序數組,同時heapsort將它排序爲9.7 ms。在C++我的歸併函數的代碼如下:
void merge(int* array, int low, int mid, int high)
{
int i, j, k;
int lowLength = mid - low + 1;
int highLength = high - mid;
int* lowArray = new int[lowLength];
int* highArray = new int[highLength];
for (i = 0; i < lowLength; i++)
lowArray[i] = array[low + i];
for (j = 0; j < highLength; j++)
highArray[j] = array[mid + 1 + j];
i = 0;
j = 0;
k = low;
while (i < lowLength && j < highLength)
{
if (lowArray[i] <= highArray[j])
{
array[k] = lowArray[i];
i++;
}
else
{
array[k] = highArray[j];
j++;
}
k++;
}
while (i < lowLength)
{
array[k] = lowArray[i];
i++;
k++;
}
while (j < highLength)
{
array[k] = highArray[j];
j++;
k++;
}
}
void mergeSort(int* array, int low, int high)
{
if (low < high)
{
int mid = low + (high - low)/2;
mergeSort(array, low, mid);
mergeSort(array, mid + 1, high);
merge(array, low, mid, high);
}
}
您正在分配。別。 – BeyelerStudios
從哪裏知道堆排序比合並排序慢?時間線性的額外拷貝操作在no。子數組的元素在堆中不存在。這使用相當精確的空間,只有最佳的東西,如何COM應該更昂貴? –
從大o符號看來,heapsort應該會變慢。 – FYOL