Home  >  Article  >  Backend Development  >  PHP Bubble Sort Binary Search Sequential Search Detailed Explanation of Two-Dimensional Array Sorting Algorithm Function_PHP Tutorial

PHP Bubble Sort Binary Search Sequential Search Detailed Explanation of Two-Dimensional Array Sorting Algorithm Function_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:03:28846browse

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

Copy code The code is as follows:

//Bubble sort (array sort)
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; }

Use PHP to describe sequential search and binary search (also called half search) algorithms. Sequential search must consider efficiency, and the object can be an ordered array
Copy code The code is as follows:

//Binary search (search for an element in an 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;
}
//Sequential search (search for an element in the array)
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;
}
}

Write a two-dimensional array sorting algorithm function, which can be universal. You can call PHP built-in function
Copy the code The code is as follows:

//Two-dimensional array sorting, $arr is the data, $keys is the key value of sorting, $order is the sorting rule, 1 is ascending order, 0 is descending order
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;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327838.htmlTechArticleData structure is very important, algorithm + data structure + document = program uses PHP to describe the bubble sort algorithm, the object can be An array copy code is as follows: //Bubble sort (array sort)...
Statement:
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