I was given an array like this:
$input = array(-1,1,3,-2,2, 3,4,-4);
I neeed to sort it in such a way that negative integers are in the front and positive integers are at the back, and the relative position should not be changed. So the output should be:
$output = array(-1 ,-2,-4, 1,3,2,3,4);
I tried this using usort
, but I could not retain the relative positions.
function cmp ($a, $b)
{
return $a - $b;
}
usort($input, "cmp");
echo '<pre>', print_r($input), '</pre>';
Array
(
[0] => -4
[1] => -2
[2] => -1
[3] => 1
[4] => 2
[5] => 3
[6] => 3
[7] => 4
)
Try this..
$arr = array(-1,1,3,-2,2, 3,4,-4);
$positive = array_filter($arr, function($x) { return $x > 0; });
$negative = array_filter($arr, function($x) { return $x < 0; });
sort($positive);
rsort($negative);
$sorted = array_merge($negative,$positive);
print_r($sorted);
Demo:https://eval.in/419320
Output:
Array
(
[0] => -1
[1] => -2
[2] => -4
[3] => 1
[4] => 2
[5] => 3
[6] => 3
[7] => 4
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With