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

I was given an array like this

$input = array(-1,1,3,-2,2, 3,4,-4); 

I need to sort it so that negative integers are in front, and positive integers are in the back, and the relative position should not change. So the output should be

 $output = array(-1 ,-2,-4, 1,3,2,3,4); 

I tried this with usort, but I could not save 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 ) 

Any thoughts?

+6
source share
2 answers

Try it.

 $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 ) 
+5
source

This is a sorting problem, but it is not sorting.

The problem can be broken down as follows:

  • Separate this array into two arrays; one of the negative numbers, the other of positive numbers. (Keep in mind where you want 0 ) The order of elements in each of these arrays should be the same as in the input array.

    Do this using push ing values.

  • The union of two arrays.

+3
source

All Articles