Data structure is very important, algorithm + data structure + document = Program
using PHP to describe the bubble sort algorithm, an object can be an array
Copy Code code 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 order lookup and binary lookup (also called binary lookup) algorithm, order lookup must consider efficiency, object can be an ordered array
Copy Code code as follows:
//Two-point lookup (Find 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 lookup (find an element in an 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 of sorting algorithm functions, can be universal, you can call PHP built-in functions
Copy Code code as follows:
//two-D array sorting, $arr is data, $keys is the sort of health value, $order is the collation, 1 is ascending, and 0 is descending
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;
}