Home>Article>Backend Development> PHP implements several sorting and search algorithms
Bubble sort, quick sort, and binary search are simple, but they are easy to forget if you don’t use them for a while. Here is the PHP implementation code that the editor found and shared with everyone to learn together.
Every time a maximum value pops up
function bubbleSort($arr) { $count = count($arr); if ($count == 0) return false; for ($i = 0; $i < $count - 1; $i++) { for ($k = 0; $k < $count - 1 - $i; $k++) { if ($arr[$k] < $arr[$k + 1]) { $tmp = $arr[$k]; $arr[$k] = $arr[$k + 1]; $arr[$k + 1] = $tmp; } } } return $arr; }
Choose a value as a benchmark , smaller ones are placed on the left, larger ones are placed on the right, then recurse to the left and right, and finally merge
function quickSort($arr) { $count = count($arr); if ($count <= 1) return $arr; $base = $arr[0]; $left = $right = []; for ($i = 1; $i < $count; $i++) { if ($arr[$i] < $base) { $left[] = $arr[$i]; } else { $right[] = $arr[$i]; } } $left = quickSort($left); $right = quickSort($right); return array_merge($left, [$base], $right); }
Select a value assumed to be the smallest, and then compare in sequence, If you find it is smaller than him, swap the positions
function selectSort($arr) { $count = count($arr); if ($count <= 1) return $arr; for ($i = 0; $i < $count; $i++) { //假设最小值位置 $p = $i; //用假设的最小值$arr[$p]轮流比较,发现比他小的就互换 for ($j = $i + 1; $j < $count; $j++) { if ($arr[$p] > $arr[$j]) { $p = $j; } } if ($p != $i) { $tmp = $arr[$p]; $arr[$p] = $arr[$i]; $arr[$i] = $tmp; } } return $arr; }
Binary search must be a sorted array, and each time the value in the middle position of the array is taken and Target comparison
function binarySearch(array $arr, $target) { $low = 0; $high = count($arr) - 1; while ($low <= $high) { $middle = floor(($high + $low) / 2); if ( $arr[$middle] == $target ) { return $middle; } elseif ( $arr[$middle] < $target ) { $low = $middle + 1; } else { $high = $middle - 1; } } return false; }
Recommended tutorial:PHP video tutorial
The above is the detailed content of PHP implements several sorting and search algorithms. For more information, please follow other related articles on the PHP Chinese website!