Home  >  Article  >  Backend Development  >  php联系关系数组排序(快速排序)

php联系关系数组排序(快速排序)

WBOY
WBOYOriginal
2016-06-13 13:11:20718browse

php关联数组排序(快速排序)

起因

好吧,我承认最近我跟快速排序干上了,各种测试编写快速排序程序,现在就用php实现快速排序,跟之前文章不同,这次php的快排是能解决实际需要的。


使用环境和条件

有这样一种情况,php里面的关联数组,如果下面这样的数组数据:

$array = array (
		array (
				'name' => "xiao",
				'age' => 3 
		),
		array (
				'name' => 'wang',
				'age' => 1 
		),
		array (
				'name' => 'chen',
				'age' => 2 
		) 
);

我们要对数组针对age字段进行排序,php自带的函数,无论是那种sort,显然都不能满足我们的需求,因此我们可以自己写一个快速排序代码,很快的实现我们的要求


注意情况

php里面是没有指针存在的,所以当想要引用传递的时候,我们不能跟C代码一样,直接这样写quicksort(int *A, int begin, int end),而是要使用php的&运算符,将数组的地址传递跟快速排序函数,这样就能在php里实现引用传递而不是值传递


快速排序代码

QuickSortProcess ( $array, 0, count ( $array ) - 1 );
print_r ( $array );

/**
 * Description:快速排序中获取中枢点的位置
 */
function QuickPartition(&$array, $left, $right) {
	// 1.基准定义
	$stand = $array [$left];
	
	// 2.从区间两端向中间扫描,直到$left == $right为止
	while ( $left = $stand ['age'] ) {
			$right --;
		}
		if ($left 
我在项目上就用到了这个快速排序,挺开心的,不枉这个10月1假期花了N天AC快速排序的c代码
1楼dickeylth昨天 14:30
这种问题可以查阅下php中的usort,写自定义的排序回调函数就行了。参见:http://www.php.net/manual/zh/function.usort.php
Re: zinss26914昨天 15:27
回复dickeylthn查了一下您给的链接,确实是这样,可以省不少代码量,多谢多谢,哈哈,其实也想在实际项目里用下自己写的排序算法,总是调用php的自带函数,感觉自己都快不会写程序了
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn