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.