Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an integer array, negative integers in the front and positive integers in the back

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
)
like image 856
Wild Widow Avatar asked Aug 20 '15 04:08

Wild Widow


1 Answers

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
)
like image 193
Deenadhayalan Manoharan Avatar answered Oct 02 '22 23:10

Deenadhayalan Manoharan