PHP bubble sort binary search sequential search detailed explanation of two-dimensional array sorting algorithm function

高洛峰
Release: 2023-03-03 21:24:01
Original
1560 people have browsed it

Data structure is very important, algorithm + data structure + document = program
Use PHP to describe the bubble sort algorithm, the object can be an array

//冒泡排序(数组排序)
function bubble_sort($array) {
$count = count($array);
if ($count <= 0)
return false;
for($i=0; $i<$count; $i++){
for($j=$count-1; $j>$i; $j–){
if ($array[$j] < $array[$j-1]){
$tmp = $array[$j];
$array[$j] = $array[$j-1];
$array[$j-1] = $tmp;
}
}
}
return $array; }
Copy after login

Use PHP to describe the sequential search and binary search (also called half search) algorithm, sequential search must Considering efficiency, the object can be an ordered array

//二分查找(数组里查找某个元素)
function bin_sch($array, $low, $high, $k){
if ($low <= $high){
$mid = intval(($low+$high)/2);
if ($array[$mid] == $k){
return $mid;
}elseif ($k < $array[$mid]){
return bin_sch($array, $low, $mid-1, $k);
}else{
return bin_sch($array, $mid+1, $high, $k);
}
}
return -1;
}
//顺序查找(数组里查找某个元素)
function seq_sch($array, $n, $k){
$array[$n] = $k;
for($i=0; $i<$n; $i++){
if($array[$i]==$k){
break;
}
}
if ($i<$n){
return $i;
}else{
return -1;
}
}
Copy after login

Write a two-dimensional array sorting algorithm function, which can be versatile and can call PHP built-in functions

//二维数组排序, $arr是数据,$keys是排序的健值,$order是排序规则,1是升序,0是降序
function array_sort($arr, $keys, $order=0) {
if (!is_array($arr)) {
return false;
}
$keysvalue = array();
foreach($arr as $key => $val) {
$keysvalue[$key] = $val[$keys];
}
if($order == 0){
asort($keysvalue);
}else {
arsort($keysvalue);
}
reset($keysvalue);
foreach($keysvalue as $key => $vals) {
$keysort[$key] = $key;
}
$new_array = array();
foreach($keysort as $key => $val) {
$new_array[$key] = $arr[$val];
}
return $new_array;
}
Copy after login

More PHP bubble sort binary search sequential search two-dimensional array sorting algorithm For detailed explanations of functions, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template