Sorting Algorithm
The sort algorithm that will be applied in this response is called Insertion Sort , or English, Insertion Sort , as it is best known.
The way that such an algorithm works resembles a person arranging their hand in 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 your hand is made up 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 stays. For example, you received the 4
card. Such a card will be placed between the 6
and 3
cards, so that your hand remains sorted from highest to lowest: [9, 7, 6, 4, 3, 1]
.
More generally, insert ordering works by traversing the list of values for each new item, and when a given condition is satisfied, insert the new element.
In the card game, the condition would be é maior que ..?
. Given the new 4
element, it traverses the [9, 7, 6, 3, 1]
list until 4
is greater than one element. From the top of the list:
-
4 > 9?
, no, continue;
-
4 > 7?
, no, continue;
-
4 > 6?
, no, continue;
-
4 > 3?
, yes, then insert new element (4) here;
Getting the final list [9, 7, 6, 4, 3, 1]
.
Figure1:Illustrativepictureofhowinsertorderingworks.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, inserting in the list one item at a time, as this will guarantee that the item will be positioned in the correct place and we will have the list sorted in the signal. Our elements are removed from the $arr
list:
$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 foreach
directive and, for each item, we insert it into the list.
$result = [];
foreach ($arr as $item)
{
$result = insert_sort($result, $item);
}
The insert_sort
function will set soon. What we are doing in this section is: for each $item
of $arr
, enter in the $result
list and update the $result
value containing the new item.
insert_sort (array $ result, mixed $ item)
The insert_sort
function receives two parameters: the list where we want to insert the item and the item to insert. The logic of the function is exactly that explained in the algorithm at the beginning of the response:
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 out: scroll through the entire list until the condition is true. Enter the new value and return the sorted list. This way, at the end, the $result
list will be:
Array
(
[0] => Array
(
[1] => 5
)
[1] => Array
(
[8] => 5
)
[2] => Array
(
[2] => 3
)
)
You can see the code working at repl.it .
Note : The condition used for sorting varies as needed. In this case, our list items are of type array
and we want to sort in a decreasing order according to the value in the first position. With the function array_values
, we return the list of all values of array
and, when accessing the index [0]
, we return only the first, thus ordering in relation to 5, 3, 5
, as given in the statement .
Optimized version
The same result can be obtained as follows:
usort($arr, function ($a, $b) {
return current($b) - current($a);
});
In this case, the $arr
list itself will be sorted. The logic executed is exactly the same, only written with fewer rows, due to the use of the function usort
and current
.
You can see the code working at repl.it .
Documentation: array_splice
, array_values
, usort
, current