Php does not use built-in functions to sort arrays.

Source: Internet
Author: User

A friend asks questions when looking for a job.
It is very likely that I will also encounter it in the future.
Problem: php does not use built-in functions to sort arrays, which may be descending or ascending.
Method 1: the legendary Bubble Method
Copy codeThe Code is as follows:
Function arraysort ($ data, $ order = 'asc '){
// Asc ascending desc descending
$ Temp = array ();
$ Count = count ($ data );
If ($ count <= 0)
Return false; // the input data is incorrect.
If ($ order = 'asc '){
For ($ I = 0; $ I <$ count; $ I ++ ){
For ($ j = $ count-1; $ j> $ I; $ j --){
If ($ data [$ j] <$ data [$ j-1]) {
// Exchange two data locations
$ Temp = $ data [$ j];
$ Data [$ j] = $ data [$ j-1];
$ Data [$ j-1] = $ temp;
}
}
}
} Else {
For ($ I = 0; $ I <$ count; $ I ++ ){
For ($ j = $ count-1; $ j> $ I; $ j --){
If ($ data [$ j]> $ data [$ j-1]) {
$ Temp = $ data [$ j];
$ Data [$ j] = $ data [$ j-1];
$ Data [$ j-1] = $ temp;
}
}
}
}
Return $ data;
}
$ Data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54, 66, 32 );
Var_dump (arraysort ($ data); // ascending
Echo ('<br> ');
Var_dump (arraysort ($ data, 'desc'); // descending order

Method 2: I don't know what name to use. Just call the insert method! Bytes
Copy codeThe Code is as follows:
Function arraysort3 ($ data, $ order = 'asc '){
// Only sort in ascending order
$ Count = count ($ data );
For ($ I = 1; $ I <$ count; $ I ++ ){
$ Temp = $ data [$ I];
$ J = $ I-1;
While ($ data [$ j]> $ temp ){
$ Data [$ j + 1] = $ data [$ j];
$ Data [$ j] = $ temp;
$ J --; // Why to decrease: Judge by bit from the high position
}
}
Return $ data;
}
$ Data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54, 66, 32 );
Var_dump (arraysort3 ($ data); // ascending

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.