Php array sorting methods

Source: Internet
Author: User

Array sorting method
There are two types:
1. Internal (memory) sorting
2. External sorting (large data volume, insufficient memory, external
Storage)


----------------
Sorting is a basic skill for programmers.
I. Internal sorting
(1) exchange sorting
1. Bubble method

By default, the array is passed as a value instead of an address.
The object type will be discussed later. The default transfer of an object is Address transfer.

// Optimization: encapsulate the bubble sorting method into a function for future use

The code is as follows: Copy code

Function bubbleSort (& $ myarr ){
$ Temp = 0; // defines an intermediate variable.
// Outer Loop
For ($ I = 0; $ I <count ($ myarr)-1; $ I ++ ){
For ($ j = 0; $ j <count ($ myarr)-1-$ I;
$ J ++ ){
If ($ myarr [$ j]> $ myarr [$ j
+ 1]) {
$ Temp = $ myarr [$ j];
$ Myarr [$ j] =
$ Myarr [$ j + 1];
$ Myarr [$ j + 1] =
$ Temp;
}

}
}
}

$ Arry = array );
BubbleSort ($ arry );
Print_r ($ arry );

2. Quick sorting (magical fast, involving recursion)

3. Select sorting method

The code is as follows: Copy code

Function selectSort (& $ myarr ){
$ Temp = 0;
For ($ I = 0; $ I <count ($ myarr)-1; $ I ++ ){
// Assume $ I is the smallest number.
$ Minval = $ myarr [$ I];
// Record the subscript of the minimum number I think
$ MinIndex = $ I;

For ($ j = $ I + 1; $ j <count ($ myarr); $ j +
+ ){
// Describe the minimum value, not the minimum value.
If ($ minval> $ myarr [$ j]) {

$ Minval = $ myarr [$ j];
$ MinIndex = $ j;

}

}
// Final exchange
$ Temp = $ myarr [$ I];
$ Myarr [$ I] = $ myarr [$ minIndex];
$ Myarr [$ minIndex] = $ temp;
}

}

4. Insert sorting method

Query speed: Bubble sort <select sort <insert sort

What I like most is exchange sorting, that is, bubble sorting. This method is easy to use, but not suitable for sorting large data volumes.

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.