Use PHP to describe the bubble sorting and quick sorting algorithms. The object can be an array.
Using PHP to describe sequential search and binary search (also called semi-query) algorithms, the efficiency of sequential search must be considered. The object can be an ordered array.
Write a two-dimensional array sorting algorithm function that is universal and can call php built-in functions
1. Use PHP to describe the bubble sort and quick sort algorithms. The object can be an array.
The code is as follows: |
Copy code |
Function bubble_sort ($ array) { $ Count = count ($ array ); If ($ count <= 0) return false; For ($ I = 0; $ I <$ count; $ I ++ ){ For ($ j = $ count-1; $ j> $ I; $ j -){ If ($ array [$ j] <$ array [$ j-1]) { $ Tmp = $ array [$ j]; $ Array [$ j] = $ array [$ j-1]; $ Array [$ j-1] = $ tmp; } } } Return $ array; } Function quick_sort ($ array ){ If (count ($ array) <= 1) return $ array; $ Key = $ array [0]; $ Left_arr = $ right_arr = array (); Foreach ($ array as $ val ){ If ($ val <= $ key) $ Left_arr [] = $ val; Else $ Right_arr [] = $ val; } $ Left_arr = quick_sort ($ left_arr ); $ Right_arr = quick_sort ($ right_arr ); Return array_merge ($ left_arr, array ($ key), $ right_arr ); }
|
2. Using PHP to describe sequential search and binary search (also called semi-query) algorithms, sequential search must take efficiency into account. The object can be an ordered array.
The code is as follows: |
Copy code |
Function bin_sch ($ array, $ low, $ high, $ k ){ If ($ low <= $ high ){ $ Mid = intval ($ low + $ high)/2 ); If ($ array [$ mid] === k ){ Return $ mid; } Elseif ($ k <$ array [$ mid]) { Return bin_sch ($ array, $ low, $ mid-1, $ k ); } Else { Return bin_sch ($ array, $ mid + 1, $ high, $ k ); } } Return-1; } Function seq_sch ($ array, $ n, $ k ){ $ Array [$ n] = $ k; For ($ I = 0; $ I <$ n; $ I ++ ){ If ($ array [$ I] === k ){ Break; } } If ($ I <$ n ){ Return $ I; } Else { Return-1; } } |
3. Write a two-dimensional array sorting algorithm function that is universal and can call php built-in functions.
The code is as follows: |
Copy code |
Function array_sort ($ arr, $ keys, $ order = 0 ){ If (! Is_array ($ arr )){ Return false; } $ Keysvalue = array (); Foreach ($ arr as $ key => $ val ){ $ Keysvalue [$ key] = $ val [$ keys]; } If ($ order = 0 ){ Asort ($ keysvalue ); } Else { Arsort ($ keysvalue ); } Reset ($ keysvalue ); Foreach ($ keysvalue as $ key => $ vals ){ $ Keysort [$ key] = $ key; } $ New_array = array (); Foreach ($ keysort as $ key => $ val ){ $ New_array [$ key] = $ arr [$ val]; } Return $ new_array; } |