php 算法五则

<?php
//冒泡排序
function maopao_sort($demo){
    
$num  = count($demo);
    
for($i=0;$i<$num;$i++){
        
for($j=$num-1;$j>$i;$j--){
            
if($demo[$j]<$demo[$j-1]){
                
$temp     = $demo[$j];
                
$demo[$j]=$demo[$j-1];
                
$demo[$j-1]= $temp;
            }
        }
    }
    
return $demo;
}

//插入排序
function charu_sort($demo){
    
$num = count($demo);
    
for($i=1;$i<$num;$i++){
        
$temp=$demo[$i];
        
$dqweizhi = $i-1;//记录当前位置
        while(($dqweizhi>=0)&&($temp<$demo[$dqweizhi])){
            
$demo[$dqweizhi+1= $demo[$dqweizhi];
            
$dqweizhi--;
        }
        
$demo[$dqweizhi+1= $temp;
    }
    
return $demo;
}

//选择法排序
function select_sort($demo){
    
$num = count($demo);
    
for($i=0;$i<$num-1;$i++){
        
$temp=$demo[$i];
        
$dqweizhi=$i;
        
for($j=$i+1;$j<$num;$j++){
            
if($demo[$j]<$temp){
                
$temp=$demo[$j];
                
$dqweizhi=$j;
            }
        }
        
$demo[$dqweizhi]=$demo[$i];
        
$demo[$i]=$temp;
    }
    
return $demo;
}

//快速排序
function quick_sort($demo)
{
$num = count($demo);
if($num<=1){
    
return $demo;
}
$key=$demo[0];
$left_array=array();
$right_array=array();
for($i=1;$i<$num;$i++){
    
if($demo[$i]<=$key){
        
$left_array[]=$demo[$i];
    }
else{
        
$right_array[]=$demo[$i];
    }
}
$left_array =quick_sort($left_array);
$right_array=quick_sort($right_array);
return array_merge($left_array,array($key),$right_array);
}

$test = array('43','154','3','78','13','284','167','2','56','2234','121','57','345');
$sss = quick_sort($test);
var_dump($sss);
 
// 二分查找实现函数
function binary_search($array, $key, $left_index, $right_index) {
    // 递归的结束条件,即未找到指定的元素。
    if ($left_index > $right_index) {
        echo "no such element!";
        return;
    }
    
    // 计算出中间索引值
    $middle_index = round(($left_index + $right_index) / 2);
    
    // 比较待查找值与数组中间值
    if ($key > $array[$middle_index]) { // 在右半边继续查找
        binary_search($array, $key, $middle_index + 1, $right_index);
    } else if ($key < $array[$middle_index]) { // 在左半边继续查找
        binary_search($array, $key, $left_index, $middle_index - 1);
    } else { // 找到指定的元素
        echo "found, the key is $middle_index in the array.";
    }
}

// 初始化数组(注意:该数组一定是有序的)
$array = array(-1, 4, 5, 6, 7, 9, 12);

// 调用函数
binary_search($array, 4, 0, count($array)); // 输出:found, the key is 1 in the array.
binary_search($array, 8, 0, count($array)); // 输出:no such element!

 

?>
posted @ 2010-03-13 00:32  般若随风  阅读(466)  评论(1编辑  收藏  举报