[Select sorting: The second number to the nth number are compared with the first number, and the third number to the nth number are compared with the second number, and exchanged until the sorting is complete]
The code is as follows: |
Copy code |
Function selectSort ($ arr, $ style) { $ Temp = 0; For ($ I = 0; $ I <count ($ arr)-1; $ I ++) { For ($ j = $ I + 1; $ j <count ($ arr); $ j ++) { If ($ style = 'bts') $ op = $ arr [$ I] <$ arr [$ j]; Else if ($ style = 'stab') $ op = $ arr [$ I]> $ arr [$ j]; If ($ op) { $ Temp = $ arr [$ I]; $ Arr [$ I] = $ arr [$ j]; $ Arr [$ j] = $ temp; } } } Foreach ($ arr as $ key => $ value) { Echo $ value .','; } } $ Arr1 = array (21.5, 7 ); SelectSort ($ arr1, 'stab '); |
[The value is passed by default, not the address. If you add an ampersands (&) before $ arr, it points to the same address as $ arr1, and $ arr1 outside the function is also arranged]
The code is as follows: |
Copy code |
Function maoPao ($ arr, $ style ){ $ Temp = 0; For ($ I = 0; $ I <count ($ arr)-1; $ I ++) { For ($ j = 0; $ j <count ($ arr)-1-$ I; $ j ++) { If ($ style = 'bts') $ op = $ arr [$ j] <$ arr [$ j + 1]; Else if ($ style = 'stab') $ op = $ arr [$ j]> $ arr [$ j + 1]; If ($ op) { $ Temp = $ arr [$ j]; $ Arr [$ j] = $ arr [$ j + 1]; $ Arr [$ j + 1] = $ temp; } } } Foreach ($ arr as $ key => $ value) { Echo $ value .','; } } $ Arr1 = array (101,101,-9,-,-56 ); MaoPao ($ arr1, 'stab'); // small to big |
[Insert sorting: The second compares with the first one, exchanges, and the third compares with the first two .... Comparison between the nth and the first n-1, exchange]
The code is as follows: |
Copy code |
Function insertSort ($ arr, $ style) { $ Temp = 0; For ($ I = 1; $ I <count ($ arr); $ I ++) { For ($ j = 0; $ j <$ I; $ j ++) { If ($ style = 'bts') $ op = $ arr [$ j] <$ arr [$ I]; Else if ($ style = 'stab') $ op = $ arr [$ j]> $ arr [$ I]; If ($ op) { $ Temp = $ arr [$ j]; $ Arr [$ j] = $ arr [$ I]; $ Arr [$ I] = $ temp; } } } Foreach ($ arr as $ key => $ value) { Echo $ value .','; } } $ Arr1 = array (, 0 ); InsertSort ($ arr1, 'bts '); |