我有兩個在C++和PHP上進行雙向合併排序的相同示例。 C++示例工作正常,但PHP不。PHP雙向合併排序
爲什麼php示例不起作用?找不到一個錯誤:
function merge($m, $low, $mid, $high)
{
$i = $low;
$j = $mid+1;
$k = 0;
$tmp = array();
while (($i <= $mid) && ($j <= $high))
{
if ($m[$i] > $m[$j])
$tmp[$k++] = $m[$i++];
else
$tmp[$k++] = $m[$j++];
}
if ($i <= $mid)
{
while ($i <= $mid)
$tmp[$k++] = $m[$i++];
}
if ($j <= $high)
{
while ($j <= $high)
$tmp[$k++] = $m[$j++];
}
for ($i = $low; $i <= $high; $i++)
$m[$i] = $tmp[$i-$low];
return $m;
}
function mergeSort($m, $low, $high)
{
if ($high > $low)
{
$middle = ($high+$low)/2;
mergeSort($m, $low, $middle);
mergeSort($m, $middle+1, $high);
merge($m, $low, $middle, $high);
}
}
$m = array(0,3,2,4);
$m = mergeSort($m, 0, 3);
echo $m[0]; // there null :(
C++爲例,它的作品罰款:
int m[10];
void merge(int low, int mid, int high)
{
int i = low;
int j = mid+1;
int z = 0;
int tmp[10] = {0};
while ((i <= mid) && (j <= high))
{
if (m[i] < m[j])
tmp[z++] = m[i++];
else
tmp[z++] = m[j++];
}
if (i <= mid)
{
while (i <= mid)
tmp[z++] = m[i++];
}
if (j <= high)
{
while (j <= high)
tmp[z++] = m[j++];
}
for (int a = low; a <= high; a++)
m[a] = tmp[a-low];
}
void mergeSort(int low, int high)
{
if (low < high)
{
int middle = (high+low)/2;
mergeSort(low, middle);
mergeSort(middle+1, high);
merge(low, middle, high);
}
return;
}
int main(array<System::String ^> ^args)
{
for (int i = 0; i < 10; i++)
m[i] = rand()%101;
mergeSort(0, 7);
for (int i = 0; i < 10; i++)
Console::WriteLine("{0}", m[i]);
Console::ReadLine();
return 0;
}
我想,有遞歸循環,因爲網頁加載時間過長。 但不知道如何檢查它。 我做錯了什麼?
php內置合併排序功能c – DevZer0
基本上你需要調試代碼,這幾乎都是錯誤的。數組的語義和按值傳遞參數在PHP中是非常不同的,你不能僅僅從C++傳遞類似的代碼並期望它能夠工作。 – Jon
這不是C++,縮進是_horrendous_。你只是代碼審查失敗,你是否在我的團隊中。 –