// 冒泡排序
function bubbleSort($arr)
{
$length = count($arr);
for ($i = 0; $i < $length; $i++) {
for ($j = $i + 1; $j < $length; $j++) {
if ($arr[$i] > $arr[$j]) {
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}
$arr = [3, 2, 9, 1, 8, 6, 7, 5, 4, 0];
print_r(bubbleSort($arr));
// 快速排序
function quickSort($arr)
{
$length = count($arr);
if ($length < 2) {
return $arr;
}
$mid = $arr[0];
$left = [];
$right = [];
for ($i = 1; $i < $length; $i++) {
if ($arr[$i] > $mid) {
$right[] = $arr[$i];
} else {
$left[] = $arr[$i];
}
}
$left = quickSort($left);
$right = quickSort($right);
return array_merge($left, [$mid], $right);
}
$arr = [3, 2, 9, 1, 8, 6, 7, 5, 4, 0];
print_r(quickSort($arr));
// 二分查找
// 递归实现
function binarySearch($arr, $targetElement, $start, $end)
{
if ($start > $end) {
return -1;
}
$mid = intval(($start + $end) / 2);
if ($arr[$mid] == $targetElement) {
return $mid;
} elseif ($arr[$mid] > $targetElement) {
$end = $mid - 1;
return binarySearch($arr, $targetElement, $start, $end);
} else {
$start = $mid + 1;
return binarySearch($arr, $targetElement, $start, $end);
}
}
// 循环实现
function binarySearch($arr, $targetElement)
{
$start = 0;
$end = count($arr) - 1;
while ($start <= $end) {
$mid = intval(($start + $end) / 2);
if ($arr[$mid] == $targetElement) {
return $mid;
} elseif ($arr[$mid] > $targetElement) {
$end = $mid - 1;
} else {
$start = $mid + 1;
}
}
return -1;
}
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
print_r(binarySearch($arr, 3, 0, count($arr)));
//无限分类递归树状结构
$arr = [
['id' => 2, 'name' => '一级分类2', 'pid' => 0],
['id' => 3, 'name' => '二级分类1-1', 'pid' => 1],
['id' => 4, 'name' => '二级分类1-2', 'pid' => 1],
['id' => 5, 'name' => '二级分类2-1', 'pid' => 2],
['id' => 6, 'name' => '二级分类2-2', 'pid' => 2],
['id' => 7, 'name' => '三级分类1-1-1', 'pid' => 3],
['id' => 1, 'name' => '一级分类1', 'pid' => 0],
['id' => 8, 'name' => '三级分类1-1-2', 'pid' => 3],
];
function tree($arr, $pid = 0)
{
$list = array();
foreach ($arr as $k => $v) {
if ($v['pid'] == $pid) {
$child = tree($arr, $v['id']);
if (count($child)) {
$v['child'] = $child;
}
$list[] = $v;
}
}
return $list;
}
print_r(tree($arr));
//遍历文件夹下所有文件
function eachFile($path)
{
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if (in_array($file, ['.', '..'])) {
continue;
}
if (is_dir($path . '/' . $file)) {
eachFile($path . '/' . $file);
} else {
echo $path . '/' . $file . "\n";
}
}
}
}
// 乘法口诀
function multiplicationTable()
{
for ($i = 1; $i < 10; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo $j . 'X' . $i . '=' . $i * $j . " ";
}
echo "\n";
}
}