What is the difference between bubble sort, quick sort, selection sort, and insert sort in PHP?
Bubble sort, quick sort, selection sort, and insert sort are all sorting algorithms used to arrange elements in a specific order. The main difference between them lies in their efficiency and performance. Bubble sort is simple but inefficient, quick sort is fast but may have a worst-case scenario, selection sort is simple but not very efficient, and insert sort is efficient for small datasets.
```php
// Bubble Sort
function bubbleSort($array) {
$n = count($array);
do {
$swapped = false;
for ($i = 0; $i < $n - 1; $i++) {
if ($array[$i] > $array[$i + 1]) {
$temp = $array[$i];
$array[$i] = $array[$i + 1];
$array[$i + 1] = $temp;
$swapped = true;
}
}
} while ($swapped);
return $array;
}
// Quick Sort
function quickSort($array) {
if (count($array) <= 1) {
return $array;
}
$pivot = $array[0];
$left = $right = [];
for ($i = 1; $i < count($array); $i++) {
if ($array[$i] < $pivot) {
$left[] = $array[$i];
} else {
$right[] = $array[$i];
}
}
return array_merge(quickSort($left), [$pivot], quickSort($right));
}
// Selection Sort
function selectionSort($array) {
$n = count($array);
for ($i = 0; $i < $n - 1; $i++) {
$min = $i;
for ($j = $i + 1; $j < $n; $j++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$temp = $array[$i];
$array[$i] = $array[$min];
$array[$min] = $temp;
}
return $array;
}
// Insert Sort
function insertSort($array) {
$n = count($array);
for ($i = 1; $i < $n; $i
Keywords
Related Questions
- Are there any specific scenarios where it is recommended to always use function_exists and class_exists?
- Warum ist es wichtig, eine echte Last-Modified Zeit für die Datei bereitzustellen, wenn der Browser einen Not Modified-Header erhält?
- Are there alternative methods to prevent duplicate data from being displayed in PHP applications without using "DISTINCT"?