php - update this quicksort algorithm to handle sorting on a specific key -
i believe if dealing jumbled sets of data, quicksort 1 of best ways of handling sorting. update following code handle arrays keys can sort list of arrays opposed values in single array.
function quicksort($array) { if (count($array) == 0) return array(); $pivot = $array[0]; $left = $right = array(); ($i = 1; $i < count($array); $i++) { if ($array[$i] < $pivot) $left[] = $array[$i]; else $right[] = $array[$i]; } return array_merge(self::quicksort($left, ''), array($pivot), self::quicksort($right, '')); }
using usort() anonymous function
<?php $arr = array( array("val" => 10, "something" => "zzz", "val2" => 1110), array("val" => 111, "something" => "aaa", "val2" => 1), array("val" => 1, "something" => "bbb", "val2" => 12), array("val" => 14, "something" => "eee", "val2" => 31), array("val" => 2, "something" => "ccc", "val2" => 11), ); usort($arr, function ($a, $b) { if ($a['val2'] > $b['val2']) { $result = 1; } elseif ($a['val2'] < $b['val2']) { $result = -1; } else { $result = 0; } return $result; }); var_dump($arr);
try thinking sort strategy design pattern
<?php class sortstrategy { public $key; public function __construct($key) { $this->key = $key; } public function cmp($a, $b) { return ($a[$this->key] > $b[$this->key]) ? 1 : (($a[$this->key] < $b[$this->key]) ? -1 : 0); } } $arr = array( array("val" => 10, "something" => "zzz", "val2" => 1110), array("val" => 111, "something" => "aaa", "val2" => 1), array("val" => 1, "something" => "bbb", "val2" => 12), array("val" => 14, "something" => "eee", "val2" => 31), array("val" => 2, "something" => "ccc", "val2" => 11), ); // sort val2 key $objsortstrategy = new sortstrategy('val2'); usort($arr, [$objsortstrategy, 'cmp']); var_dump($arr); // sort val key $objsortstrategy->key = 'val'; usort($arr, [$objsortstrategy, 'cmp']); var_dump($arr); // sort key $objsortstrategy->key = 'something'; usort($arr, [$objsortstrategy, 'cmp']); var_dump($arr);
note: quick example give ideas
Comments
Post a Comment