Sort an array of numbers by another predefined, non-exhaustive array of number, then sort ascending

Viewed 251

Given two arrays $A1 and $A2, sort $A1 in such a way that the relative order among the elements will be same as those in $A2. For the elements not present in $A2, move them to the back of the array in ascending order.

$A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8];
$A2 = [2, 1, 8, 3];

Desired output:

[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]

Coding attempt:

$sorted = array();

foreach($a1 as $key => $value) {
    if(in_array($value, $a2)) {
        $sorted[array_search($value, $a1)] = $value;
    }
}
4 Answers

This can be done via for each loop :

$arr1 = array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8); // array to be sorted
$arr2 = array(2, 1, 8, 3); // refrence array for sort logic
// Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

$sortarr = array(); // array to store final sorted values
foreach ($arr2 as $a) {
    foreach ($arr1 as $k => $b) {
        if($b==$a) {
            $sortarr[]=$b;
            unset($arr1[$k]);
        }
    }

}

$finalarr = array_merge($sortarr, $arr1);

print_r($finalarr);

You can use usort like this:

$k = array_flip($a2); // Create an associative array for the second array
usort($a1, function($a, $b) use ($k) {
    return isset($k[$a]) ? (isset($k[$b]) ? $k[$a]-$k[$b] : -1) : (isset($k[$b]) ? 1 : $a-$b);
});

Other solutions that use a nested loop result in a time complexity of O(n²), while this has a time complexity of O(nlogn).

i tried this code and works:

<?php
/*
Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
       A2[] = {2, 1, 8, 3}
Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

*/
$a1=array(2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8);
$a2=array(2, 1, 8, 3);
$a3=array();

sort($a1);//order array
//order array a3 with a2 value....
for($i=0;$i<sizeof($a2);$i++){
  for($j=0;$j<sizeof($a1);$j++){
    if($a1[$j]==$a2[$i]){
      array_push($a3,$a2[$i]);
      //if exsist value i change value in a1 in x
      $a1[$j]="x";
    }
  }
}
//write in a3 the next number not present in a2
for($i=0;$i<sizeof($a1);$i++){
  if($a1[$i]<>"x"){
    array_push($a3, $a1[$i]);
  }
}
print_r($a3);
//out:Array ( [0] => 2 [1] => 2 [2] => 1 [3] => 1 [4] => 8 [5] => 8 [6] => 3 [7] => 5 [8] => 6 [9] => 7 [10] => 9 )
 ?>

Hope this helps

I do not endorse the use of nested loops because they will be doing too many unnecessary cycles. @trincot's approach moreso represents what I would use in a professional application, but I will demonstrate a more modern and concise style with no iterated function calls.

Code: (Demo)

$arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8];
$arr2 = [2, 1, 8, 3];

$priority = array_flip($arr2);
$fallback = count($arr2);

usort(
    $arr1,
    fn($a, $b) =>
        [$priority[$a] ?? $fallback, $a]
        <=>
        [$priority[$b] ?? $fallback, $b]
);
var_export($arr1);
// [2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]

$arr2 is flipped into a lookup array, and count() is used when a value is not found in the lookup array. Whenever the first rule results in a tie, the second rule orders the numbers numerically in an ascending direction.

The meaning of custom function's syntax is:

[left value rule1, left value rule2] compared to [right value rule1, right value rule2]

The spaceship operator (<=>) will compare the corresponding element one at a time "rule1 vs rule1" then "rule2 vs rule2" as needed.

Related