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