php实现一些快速排序算法

本文分享了作者使用PHP实现的插入排序和快速排序算法,并提供了完整的类定义及排序过程。适合初学者了解排序算法的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久没来逛博客了,实在是因为项目太忙的缘故,抽不出时间来写,对不住关注我博客的同学了。最近复习了一下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即为排序好的数组

以后有时间会经常更新自己的博客,贴出自己的原创性代码供大家学习讨论,感谢大家关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值