我有一个问题要处理这里(一个逻辑错误在我的代码99%)。我似乎就是找不到解决它的方法,但我敢打赌你们中的一个很快就会找到问题所在!
我必须创建一个函数来对传递给它的数组按asc或desc顺序排序,但不能使用任何数组排序函数!
我一直在与循环斗争,直到现在,我终于想向其他开发人员(你)寻求帮助。
目前只有升序的代码在工作,降序将没有问题,我想一旦我做了这个。它在某种程度上对值进行排序,但随后停止(如果下一个最小的值在传递的数组末尾,它就会停止)。我能做些什么来防止这种情况,让它对整个数组及其元素排序?
这是到目前为止的代码。
<?php
function order_array($array,$mode = 'ascending') {
$length = count($array);
if($mode == 'descending') {
return $array;
} else {
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
}
return $sorted_array;
}
}
$array_to_sort = array(1, 3, 100, 99, 33, 20);
$sorted_array = order_array($array_to_sort);
print_r($sorted_array);
?>
我已经用完全不同的方法解决了这个问题。现在它对传入数组的所有元素进行了正确排序。我遇到的逻辑问题是使用for()循环。for()循环只运行了set(传入数组的长度)的次数,而我们需要它循环更多的次数,因为我们需要一直循环,直到我们得到一个按升序排序的新数组。下面是将起作用的代码
function order_array($array,$mode = 'ascending') {
if($mode == 'descending') {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MAX($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
} else {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MIN($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
}
}
function order_array($array,$mode = 'ascending') {
$length = count($array);
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
if($mode == 'descending') {
return array_reverse($sorted_array);
}
return $sorted_array;
}
}