在PHP中排序一个整数数组,前面是负整数,后面是正整数

时间:2022-06-15 16:00:04

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.

我尝试使用usort,但我无法保留相对位置。

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?

2 个解决方案

#1


5  

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
)

#2


3  

This is an ordering problem, but it's not a sort.

这是一个排序问题,但它不是一种排序。

The problem can be broken down as follows:

问题可以分解如下:

  1. Separate the given array into two arrays; one of negative numbers, the other of positive numbers. (Should consider where you want 0.) The order of items in each of those arrays should be the same as they appear in the input array.

    将给定的数组分成两个数组;一个是负数,另一个是正数。 (应该考虑你想要的位置0.)每个数组中项目的顺序应该与它们在输入数组中出现的顺序相同。

    Do this by pushing values, for example.

    例如,通过推送值来做到这一点。

  2. Concatenate the two arrays.

    连接两个数组。

#1


5  

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
)

#2


3  

This is an ordering problem, but it's not a sort.

这是一个排序问题,但它不是一种排序。

The problem can be broken down as follows:

问题可以分解如下:

  1. Separate the given array into two arrays; one of negative numbers, the other of positive numbers. (Should consider where you want 0.) The order of items in each of those arrays should be the same as they appear in the input array.

    将给定的数组分成两个数组;一个是负数,另一个是正数。 (应该考虑你想要的位置0.)每个数组中项目的顺序应该与它们在输入数组中出现的顺序相同。

    Do this by pushing values, for example.

    例如,通过推送值来做到这一点。

  2. Concatenate the two arrays.

    连接两个数组。