各种排序算法+折半查找

冒泡

public function action_bubble()
    {

    	$arr = array(10, 8, 5, 11, 9);
    	for($i=0; $i $arr[$j+1])
    			{
    				$swap = $arr[$j];
    				$arr[$j] = $arr[$j+1];
    				$arr[$j+1] = $swap;
    			}

    		}
    	}

    	print_r($arr); exit;
    }

选择

public function action_select()
    {
    	$arr = array(10, 8, 5, 11, 9);
    	for($i=0; $i
插入

 public function action_insert()
    {
    	$arr = array(10, 8, 5, 11, 9);
    	foreach($arr as $k=>$v)
    	{
    		$i = $k-1;
    		while($i > -1 && $arr[$i] < $v)
    		{
    			$swap = $arr[$i+1];
    			$arr[$i+1] = $arr[$i];
    			$arr[$i] = $swap;
    			$i--;
    		}
    	}
    	print_r($arr); exit;
    }
快速

public function action_quick()
	{
		$arr=array(10, 8, 5, 11, 9);
		$new_arr = $this->quick2($arr);
		print_r($new_arr); exit;
	}


    public function quick2($arr)
    {
    	$len = count($arr);
    	if($len <= 1)
    		return $arr;
    	$x = array();
    	$y = array();
    	$k = $arr[0];
    	for($i=1; $i<$len; $i++)
    	{
    		if($arr[$i] <= $k)
    		{
    			$x[] = $arr[$i];
    		}else{
    			$y[] = $arr[$i];
    		}
    	}
    	$x = $this->quick2($x);
    	$y = $this->quick2($y);
    	$res = array_merge($x, array($k), $y);
    	return $res;
    }

折半查找

public function action_find()
    {
    	$arr=array(5, 9, 10, 11, 26);
		$pos = $this->find_me($arr, 10);
		echo $arr[$pos]; exit;
    }

    public function find_me($arr, $x)
    {
    	$l = 0;
    	$r = count($arr);
    	while($l <= $r)
    	{
    		$mid = floor(($l+$r)/2);
    		if($x > $arr[$mid])
    			$l = $mid+1;
    		elseif($x < $arr[$mid])
    			$r = $mid-1;
    		else
    			return $mid;


    	}
    }





你可能感兴趣的:(各种排序算法+折半查找)