A detailed explanation of the PHP sort usage

Source: Internet
Author: User

How many sort functions in PHP do you write this yourself?! Then think about it, I was wrong, programming is not rote mechanical movement, but also a collection of multiple thinking; The aim of the algorithm is to expand the purpose of his thinking.

So I tried to write it.
  
   
   
<?php Tutorial
$array = Array (10,5,36,86,2,56,9,15,8,4,3,41);
$num = count ($array);
for ($i = 0; $i < $num-1; $i + +) {
for ($j = $i +1; $j < $num; $j + +) {
if ($array [$j]> $array [$i]) {///here Exchange the value of the array
$temp = $array [$i];
$array [$i] = $array [$j];
$array [$j] = $temp;
}
}
}
Print_r ($array);
?>
This is the write bubble sort algorithm, and the result is OK:
  
   
   
----------PHP Debug----------
Array
(
[0] => 86
[1] => 56
[2] => 41
[3] => 36
[4] => 15
[5] => 10
[6] => 9
[7] => 8
[8] => 5
[9] => 4
[Ten] => 3
[One] => 2
)

Output complete (time consuming 0 seconds)-Normal termination
Looking at the small joy of success, and then wrote another, so the problem came out-
  
   
   
<?php
$array = Array (10,5,36,86,2,56,9,15,8,4,3,41);
$num = count ($array);
For ($i =0 $i < $num-1; $i + +) {
for ($j = $i +1; $j < $num; $j + +) {
if ($array [$j]> $array [$i]) {//Here is the Exchange key value
$temp = $i;
$i = $j;
$j = $temp;
}
}
}
Print_r ($array);
?>
The result is appalling ...
 
   
   
----------PHP Debug----------
Array
(
[0] => 10
[1] => 5
[2] =>
[3] =>
[4] => 2
[5] =>,
[6] => 9
[7] =>
[8] => 8
[9] => 4
[] => 3
[one] =>
)

Output complete (time consuming 0 seconds)-Normal termination

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.