Home > Web Front-end > JS Tutorial > body text

The difference between quick sorting php and javascript_javascript skills

WBOY
Release: 2016-05-16 18:10:29
Original
1512 people have browsed it
1. PHP
复制代码 代码如下:

$unsorted = array(2,4,5,63,4,5,63,2,4,43);
function quicksort($array)
{
if (count($array) == 0)
return array();
$pivot = $array[0];
$left = $right = array();
for ($i = 1; $i < count($array); $i ) {
if ($array[$i] < $pivot)
$left[] = $array[$i];
else
$right[] = $array[$i];
}
return array_merge(quicksort($left), array($pivot), quicksort($right));
}
$sorted = quicksort($unsorted);
print_r($sorted);

2. JavaScript
复制代码 代码如下:

var a = [2,4,5,63,4,5,63,2,4,43];
function quicksort(arr)
{
if (arr.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = arr[0];
for (var i = 1; i < arr.length; i ) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
console.log(quicksort(a));

注意,第一个条件语句是很重要的!而在PHP中COUNT函数将返回一个NULL值或空数组或0代替,你可以像count($array)<2的东西它
复制代码 代码如下:

if (count($array) < 2)
return $array;

在JavaScript中你无法使用,由于对'未定义'的值时,存在一个“空“数组作为参数传递。因此,需要包含上面的条件:
复制代码 代码如下:

// this will result with an error
if (arr.length < 2)
return arr;
Related labels:
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!