|
好久没来逛博客了,实在是因为项目太忙的缘故,抽不出时间来写,对不住关注我博客的同学了。最近复习了一下c语言,将C语言的一些排序算法用php实现了一下,贴出来大家供大家学习指正。
php实现插入排序
/**
* Description:php实现插入排序的类
* @author wzy
*/
class insert_sort {
public $arr;
public $size;
function __construct($arr) {
$this->arr = $arr;
$this->size = count ( $arr );
}
//引用传递,实现数据值的交换
function swap(&$a, &$b) {
list ( $a, $b ) = array ($b, $a );
}
//插入排序主逻辑函数
function insert_sort_process() {
for($j = 1; $j < $this->size; $j ++) {
$key = $this->arr [$j];
$i = $j - 1;
while ( $i >= 0 && $this->arr [$i] > $key ) {
$this->swap ( $this->arr [$i], $this->arr [$i + 1] );
$i --;
}
//$i+1是因为退出while循环时进行了减一操作
$this->arr [$i + 1] = $key;
}
return $this->arr;
}
}
php实现快速排序
/**
* Description:php实现快速排序类
*
* @author wzy
*
*/
class quick_sort {
public $arr;
public $size;
function __construct($array) {
$this->arr = $array;
$this->size = count ( $array );
}
function quick_swap(&$a, &$b) {
list ( $a, $b ) = array ($b, $a );
}
//获取分段数据位置
function quick_partiton($left, $right) {
$key = $this->arr [$left];
$i = $left + 1;
$j = $right;
while ( $i <= $j ) {
while ( $i <= $j && $this->arr [$i] <= $key ) {
$i ++;
}
while ( $i <= $j && $this->arr [$j] > $key ) {
$j --;
}
if ($i < $j) {
$this->quick_swap ( $this->arr [$i], $this->arr [$j] );
}
}
$this->quick_swap ( $this->arr [$left], $this->arr [$j] );
return $j;
}
//快速排序主逻辑函数
function quick_sort_process($left = null, $right = null) {
$left = (is_null ( $left )) ? 0 : $left;
$right = (is_null ( $right )) ? $this->size - 1 : $right;
if ($left < $right) {
$middle = $this->quick_partiton ( $left, $right );
$this->quick_sort_process ( $left, $middle - 1 );
$this->quick_sort_process ( $middle + 1, $right );
}
}
}
调用$this->arr即为排序好的数组
以后有时间会经常更新自己的博客,贴出自己的原创性代码供大家学习讨论,感谢大家关注 |
|
|