Quickly sort the differences between PHP and JavaScript _javascript tips

Source: Internet
Author: User
Tags php and
1. PHP
Copy Code code as follows:

<?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
Copy Code code as follows:

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);
}
Console.log (Quicksort (a));

Note that the first conditional statement is very important! And in PHP the Count function returns a null value or an empty array or 0 instead, you can <2 things like count ($array) it
Copy Code code as follows:

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

You can't use it in JavaScript, because there is an "empty" array to pass as a parameter for ' undefined ' values. Therefore, you need to include the above criteria:
Copy Code code as follows:

This'll result with the An error
if (Arr.length < 2)
return arr;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.