我试图将排序方法从Javascript转换为php,我遇到了一些麻烦。
代码如下:
private static function quicksort($ids, $dists, $left, $right) {
if ($right - $left <= 20) {
for ($i = $left + 1; $i <= $right; $i++) {
$temp = $ids[$i];
$tempDist = $dists[$temp];
$j = $i - 1;
while ($j >= $left && $dists[$ids[$j]] > $tempDist) {
$ids[$j + 1] = $ids[$j--];
}
$ids[$j + 1] = $temp;
}
} else {
$median = ($left + $right) >> 1;
$i = $left + 1;
$j = $right;
self::swap($ids, $median, $i);
if ($dists[$ids[$left]] > $dists[$ids[$right]]) self::swap($ids, $left, $right);
if ($dists[$ids[$i]] > $dists[$ids[$right]]) self::swap($ids, $i, $right);
if ($dists[$ids[$left]] > $dists[$ids[$i]]) self::swap($ids, $left, $i);
$temp = $ids[$i];
$tempDist = $dists[$temp];
while (true) {
do $i++; while ($dists[$ids[$i]] < $tempDist);
do $j--; while ($dists[$ids[$j]] > $tempDist);
if ($j < $i) break;
self::swap($ids, $i, $j);
}
$ids[$left + 1] = $ids[$j];
$ids[$j] = $temp;
if ($right - $i + 1 >= $j - $left) {
self::quicksort($ids, $dists, $i, $right);
self::quicksort($ids, $dists, $left, $j - 1);
} else {
self::quicksort($ids, $dists, $left, $j - 1);
self::quicksort($ids, $dists, $i, $right);
}
}
}
private static function swap($arr, $i, $j) {
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
我使用以下参数运行此代码:
并在此行显示一条错误,提示未定义偏移:161
do $i++; while ($dists[$ids[$i]] < $tempDist);