PHP常用算法
1.冒泡排序
function bubbleSort ($array) {
$n = count($array);
for ($i = 0; $i < $n -1; ++$i) {
$swap = false;
for ($j = 0; $j < $n - 1 - $i; ++$j) {
if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
$swap = true;
}
}
if (!$swap) {
break;
}
}
return $array;
}
2.快速排序
<?php
function quickSort($array)
{
if (count($array) <= 1) {
return $array;
}
$mid = $array[0];
$left = [];
$right = [];
for ($i = 1; $i < count($array); $i++) {
if ($array[$i] < $mid) {
$left[] = $array[$i];
} else {
$right[] = $array[$i];
}
}
$left = quickSort($left);
$right = quickSort($right);
return array_merge($left, [$mid], $right);
}
$array = [2, 1, 10, 5, 6, 12, 33, 3];
echo json_encode(quickSort($array));
3.二分查找(必须有序)
<?php
function binarySearch($array, $search)
{
$left = 0;
$right = count($array) - 1;
while ($left <= $right) {
$key = intval(($left + $right) / 2);
$mid = $array[$key];
if ($search == $mid) {
return $key;
}
if ($search > $mid) {
$left = $key + 1;
}
if ($search < $mid) {
$right = $mid - 1;
}
}
return -1;
}
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
echo binarySearch($array, 6);
4.归并排序
<?php
function mergeSort(array $array) {
// 如果数组长度小于等于1,直接返回
if (count($array) <= 1) {
return $array;
}
// 分割数组
$mid = floor(count($array) / 2);
$left = mergeSort(array_slice($array, 0, $mid));
$right = mergeSort(array_slice($array, $mid));
// 合并已排序的子数组
return merge($left, $right);
}
function merge(array $left, array $right) {
$result = [];
echo "left: " . json_encode($left) . "\r\n";
echo "right: " . json_encode($right) . "\r\n------\r\n";
while (count($left) > 0 && count($right) > 0) {
if ($left[0] < $right[0]) {
$result[] = array_shift($left);
} else {
$result[] = array_shift($right);
}
}
return array_merge($result, $left, $right);
}
// 示例用法
$array = [38, 27, 43, 3, 9, 82, 10];
$sortedArray = mergeSort($array);
print_r($sortedArray); // 输出: [3, 9, 10, 27, 38, 43, 82]
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »