Home > Backend Development > PHP Tutorial > Basic data structure implemented by PHP

Basic data structure implemented by PHP

巴扎黑
Release: 2023-03-01 11:58:01
Original
2254 people have browsed it

//--------------------
//Basic data structure
//------------------ --

//Binary search (search for an element in an array)
functionbin_sch($array,$low,$high,$k){
if($low<=$high){
$mid=intval((( $low+$high)/2);
if($array[$mid]==$k){
return$mid;
}elseif($k<$array[$mid]){
returnbin_sch($array, $low,$mid-1,$k);
}else{
returnbin_sch($array,$mid+1,$high,$k);
}
}
return-1;
}


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

//Deletion of linear table (implemented in array)
functiondelete_array_element($array,$i)
{
$len=count($array);
for($j=$i;$j<$len ;$j++){
$array[$j]=$array[$j+1];
}
array_pop($array);
return$array;
}

//Bubble sort (array sort)
functionbubble_sort($array)
{
$count=count($array);
if($count<=0)returnfalse;

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;
}

//quick Sorting (array sort)
functionquicksort($array){
if(count($array)<=1)return$array;

$key=$array[0];
$left_arr=array();
$ right_arr=array();

for($i=1;$iif($array[$i]<=$key)
$left_arr[]=$ array[$i];
else
$right_arr[]=$array[$i];
}

$left_arr=quicksort($left_arr);
$right_arr=quicksort($right_arr);

returnarray_merge($left_arr ,array($key),$right_arr);
}

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