我正在尝试对包含国家列表及其运动员人数的阵列进行递归快速排序
例如此输入:
[Iran, Islamic Republic Of] => 38
[Italy] => 257
[Brazil] => 246
[Norway] => 114
[Algeria] => 17
[Bulgaria] => 65
[Malaysia] => 29
我正在尝试使用此功能将信息从最高到最低排序:
function quicksort($array)
{
if (count($array) == 0) {
return array();
}
$pivot = array_shift($array); //Array_shift is getting rid of keys I need the keys to identify the numbers
$left = $right = array();
foreach($array as $key => $object){
if ($object > $pivot) {
$left[$key] = $object;
} else {
$right[$key] = $object;
}
}
return array_merge(quicksort($left), array($pivot), quicksort($right));
}
输出结果为:
[2] => 520
[3] => 512
[4] => 482
[5] => 448
[6] => 417
[7] => 378
[8] => 357
问题是我丢失了密钥(国家/地区),而我只剩下每个密钥的值。
答案 0 :(得分:0)
尝试内置数组排序功能。 arsort()
应该做到这一点。
答案 1 :(得分:0)
您应该在函数的最后一行(以return
开头的行)设置pivot的键。这应该有效:
function quicksort($array)
{
if (count($array) == 0) {
return array();
}
reset($array); // Reset array pointer to the first element
$pivotkey = key($array); // Get the key of that first element
$pivot = array_shift($array); // Het it's value and remove it
$left = $right = array();
foreach ($array as $key => $value) {
if ($value > $pivot) {
$left[$key] = $value;
} else {
$right[$key] = $value;
}
}
return array_merge(quicksort($left), array($pivotkey => $pivot), quicksort($right));
}