Home > Article > Backend Development > Basic data structure implemented by PHP
//--------------------
//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;$i
$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);
}