Na vida de um programador, mais tarde ou mais cedo, existe a necessidade de ordenar informação de diversa ordem. Para tal, torna-se necessária a utilização de algoritmos de ordenação, cada um com as suas características e desempenho. Neste artigo iremos ver alguns dos algoritmos mais utilizados, com exemplos em PHP:
- Bubble Sort:
O Bubble Sort é um algoritmo simples de ordenação que compara pares de elementos adjacentes e troca-os de posição se estiverem na ordem errada.
Exemplo em PHP:
function bubbleSort($array) {
$n = count($array);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
}
}
}
return $array;
}
$array = [3, 1, 4, 2, 5];
print_r(bubbleSort($array));
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
- Selection Sort:
O Selection Sort é um algoritmo de ordenação que encontra o menor elemento em cada passo e coloca-o no início do array.
Exemplo em PHP:
function selectionSort($array) {
$n = count($array);
for ($i = 0; $i < $n - 1; $i++) {
$minIndex = $i;
for ($j = $i + 1; $j < $n; $j++) {
if ($array[$j] < $array[$minIndex]) {
$minIndex = $j;
}
}
$temp = $array[$i];
$array[$i] = $array[$minIndex];
$array[$minIndex] = $temp;
}
return $array;
}
$array = [3, 1, 4, 2, 5];
print_r(selectionSort($array));
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
- Insertion Sort:
O Insertion Sort é um algoritmo de ordenação que percorre o array, inserindo cada elemento na sua posição correcta, na parte já ordenada do array.
Exemplo em PHP:
function insertionSort($array) {
$n = count($array);
for ($i = 1; $i < $n; $i++) {
$key = $array[$i];
$j = $i - 1;
while ($j >= 0 && $array[$j] > $key) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $key;
}
return $array;
}
$array = [3, 1, 4, 2, 5];
print_r(insertionSort($array));
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
- Merge Sort:
O Merge Sort é um algoritmo de ordenação que divide o array em dois subarrays, ordena-os separadamente e, em seguida, junta-os num único array ordenado.
Exemplo em PHP:
function mergeSort($array) {
$n = count($array);
if ($n <= 1) {
return $array;
}
$mid = (int) ($n / 2);
$left = array_slice($array, 0, $mid);
$right = array_slice($array, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right) {
$result = [];
$i = 0;
$j = 0;
while ($i < count($left) && $j < count($right)) {
if ($left[$i] <= $right[$j]) {
$result[] = $left[$i];
$i++;
} else {
$result[] = $right[$j];
$j++;
}
}
while ($i < count($left)) {
$result[] = $left[$i];
$i++;
}
while ($j < count($right)) {
$result[] = $right[$j];
$j++;
}
return $result;
}
$array = [3, 1, 4, 2, 5];
print_r(mergeSort($array));
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
- Quick Sort:
O Quick Sort é um algoritmo de ordenação que escolhe um elemento como pivot e divide o array em dois subarrays, um com os elementos menores que o pivot e outro com os elementos maiores. Em seguida, aplica a mesma operação recursivamente em ambos os subarrays.
Exemplo em PHP:
function mergeSort($array) {
$n = count($array);
if ($n <= 1) {
return $array;
}
$mid = (int) ($n / 2);
$left = array_slice($array, 0, $mid);
$right = array_slice($array, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right) {
$result = [];
$i = 0;
$j = 0;
while ($i < count($left) && $j < count($right)) {
if ($left[$i] <= $right[$j]) {
$result[] = $left[$i];
$i++;
} else {
$result[] = $right[$j];
$j++;
}
}
while ($i < count($left)) {
$result[] = $left[$i];
$i++;
}
while ($j < count($right)) {
$result[] = $right[$j];
$j++;
}
return $result;
}
$array = [3, 1, 4, 2, 5];
print_r(mergeSort($array));
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Espero que esses exemplos ajudem a entender melhor estes algoritmos de ordenação em PHP.
![](https://i0.wp.com/bitsebytes.pt/wp-content/uploads/2023/03/CC-2018-970x90-1.png?ssl=1)