Sorting Algorithm
The sort algorithm that will be applied in this answer is called Sorting by Insertion, or English, Insertion Sort, as is best known.
The way such an algorithm works resembles a person organizing his hand into a card game. Imagine that in this game you have 5 cards in your hand, sorted numerically. Disregarding the different suits and focusing only on the numbers, let’s assume that your hand is composed of [9, 7, 6, 3, 1]
. When you receive a new card in the round, you will place it in your hand so that the order remains. For example, you received the letter 4
. Such a card will be positioned between the cards 6
and 3
, so that your hand remains ordered from the largest to the smallest: [9, 7, 6, 4, 3, 1]
.
In more general terms, insertion sorting works by scrolling through the list of values for each new item and, when a particular condition is met, enter the new element.
In the card game, the condition would be é maior que ..?
. Given the new element 4
, scroll through the list [9, 7, 6, 3, 1]
until 4
is larger than an element. From the beginning of the list:
4 > 9?
, no, go on;
4 > 7?
, no, go on;
4 > 6?
, no, go on;
4 > 3?
, yes, then enter the new element (4) here;
Getting the final list [9, 7, 6, 4, 3, 1]
.
Figure 1: Figure illustrating how the insertion sorting works. Source: w3resource
PHP code
First, let’s assume that our list of elements is defined as:
$result = [];
As we wish to order a complete list, we will follow the idea presented in the algorithm, entering one item at a time in the list, as this will ensure that the item will be positioned in the correct place and we will have the ordered list in the signal. Our elements are removed from the list $arr
:
$arr = [
0 => [1 => 5],
1 => [2 => 3],
2 => [8 => 5]
];
In PHP, to go through all the items in a list, we can use the directive foreach
and, for each item, we insert it in the list.
$result = [];
foreach ($arr as $item)
{
$result = insert_sort($result, $item);
}
The function insert_sort
we will define soon. What we are doing in this passage is: for each $item
of $arr
, insert into the list $result
and update the value of $result
containing the new item.
insert_sort(array $result, Mixed $item)
The function insert_sort
receives two parameters: the list where we want to insert the item and the item to be inserted. Function logic is exactly the one explained in the algorithm at the beginning of the answer:
function insert_sort($result, $item)
{
// Variável de controle da posição na lista:
$index = 0;
// Percorre a lista:
foreach ($result as $j => $value)
{
// Verifica a condição: (novo item) > (item da lista)?
if (array_values($item)[0] > array_values($value)[0])
{
// Sim, então pare de percorrer a lista
break;
}
// Não, então continue para a próxima posição:
$index++;
}
// O novo item será inserido na posição $index
// Para isso, precisamos abrir o espaço na lista com a função array_splice:
array_splice($result, $index, 0, array($item));
// Retorne a lista ordenada:
return $result;
}
As commented: Scroll through the entire list until the condition is true. Enter the new value and return to the sorted list. Thus, at the end, the list $result
will be:
Array
(
[0] => Array
(
[1] => 5
)
[1] => Array
(
[8] => 5
)
[2] => Array
(
[2] => 3
)
)
You can see the code working on repl it..
Note: The condition used for sorting varies depending on the need. In this case, our list items are of the type array
and we want to sort down according to the value in the first position. With the function array_values
, return the list of all values of array
and, when accessing the index [0]
, we return only the first, ordering, in this way, in relation to the values 5, 3, 5
, as stated above.
Optimized version
The same result can be obtained as follows::
usort($arr, function ($a, $b) {
return current($b) - current($a);
});
In this case, the list itself $arr
will be sorted. The executed logic is exactly the same, only written with fewer lines, due to the use of the function usort
and current
.
You can see the code working on repl it..
Documentation: array_splice
, array_values
, usort
, current
arsort or rsort -> https://secure.php.net/manual/en/function.arsort.php https://secure.phnet/manual/pt_BR/function.rsort.php, that’s what you need?
– Marcelo Diniz