Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-06 19:46:59
Original
1004 people have browsed it

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 使用环境和条件 有这样一种情况,php里面的 关联 数组 ,如果下面这样的 数组 数据: [php] $array = array ( array ( 'name' = "xiao", 'age' = 3 ), array ( 'name' = 'wang', 'age' = 1 ),

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

  使用环境和条件

  有这样一种情况,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里实现引用传递而不是值传递

  快速排序代码

  [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

  while ( $left = $stand ['age'] ) {

  $right --;

  }

  if ($left

  $array [$left ++] = $array [$right];

  }

  while ( $left

  $left ++;

  }

  if ($left

  $array [$right --] = $array [$left];

  }

  }

  // 3.获取中枢点位置

  $array [$left] = $stand;

  return $left;

  }

  /**

  * Description:快速排序主流程函数

  */

  function QuickSortProcess(&$array, $begin, $end) {

  // 1.变量定义

  $pivot = NULL; // 中枢点

  if ($begin

  $pivot = QuickPartition ( $array, $begin, $end );

  QuickSortProcess ( $array, $begin, $pivot - 1 );

  QuickSortProcess ( $array, $pivot + 1, $end );

  }

  }

  我在项目上就用到了这个快速排序,挺开心的,不枉这个10月1假期花了N天AC快速排序的c代码

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!