Array sorting problems

Source: Internet
Author: User
Tags array sort

<?php
$arr = Array (23,3,43,5,56,56,33,5,5);
Insert sort (one-dimensional array)
function Insert_sort ($arr) {
$count = count ($arr);
for ($i =1; $i < $count; $i + +) {
$tmp = $arr [$i];
$j = $i-1;
while ($arr [$j] > $tmp) {
$arr [$j +1] = $arr [$j];
$arr [$j] = $tmp;
$j--;
}
}
return $arr;
}

Select sort (one-dimensional array)
function Select_sort ($arr) {
$count = count ($arr);
for ($i =0; $i < $count; $i + +) {
$k = $i;
for ($j = $i +1; $j < $count; $j + +) {
if ($arr [$k] > $arr [$j])
$k = $j;
if ($k!= $i) {
$tmp = $arr [$i];
$arr [$i] = $arr [$k];
$arr [$k] = $tmp;
}
}
}
return $arr;
}

Bubble sort (one-dimensional array)
function Bubble_sort ($array) {
$count = count ($array);
if ($count <= 0) return false;

for ($i =0; $i < $count; $i + +) {
for ($j = $count-1; $j > $i; $j-) {
if ($array [$j] < $array [$j-1]) {
$tmp = $array [$j];
$array [$j] = $array [$j-1];
$array [$j-1] = $tmp;
}
}
}
return $array;
}

Quick sort (one-dimensional array)
function Quick_sort ($array) {
if (count ($array) <= 1) return $array;

$key = $array [0];
$left _arr = Array ();
$right _arr = Array ();
for ($i =1; $i <count ($array); $i + +) {
if ($array [$i] <= $key)
$left _arr[] = $array [$i];
Else
$right _arr[] = $array [$i];
}
$left _arr = Quick_sort ($left _arr);
$right _arr = Quick_sort ($right _arr);

Return Array_merge ($left _arr, Array ($key), $right _arr);
}

?>

«Show all external variables within PHP program the ascending, descending and reordered functions of the array elements in PHP rsort (), sort (), Asort (), Ksort ()»
The array sort function of PHP
Sort ()
In ascending alphabetical order, case-sensitive, all uppercase letters preceded by lowercase letters

Asort () and Ksort ()
Sort the related array, Asort () to order the value, and Ksort () to sort the code

Rsort (), Arsort (), Krsort ()
Reverse sort function

Natsort ()
Sort the array with the natural sort algorithm

Natcasesort ()
Sort the case-insensitive alphabetical array using the "natural sort" algorithm

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.