PHP bubble sorting and binary searching for instances. We learned the bubble sort and binary search sort algorithms when we were in junior high school. next I will introduce some examples of the bubble sort and binary search in PHP. We learned how to sort by the code bubble method and the binary search sorting algorithm in junior high school. next I will introduce the examples of sorting by the PHP bubble method and the binary search.
| The code is as follows: |
|
// Sort by bubble // Random array $ Arr = array (89,112,321,234 ); // Statistics array $ Num = count ($ arr ); // Bubble sort in reverse order For ($ I = 0; $ I <$ num-1; $ I ++ ){ For ($ m = 0; $ m <$ num-1; $ m ++ ){ If ($ arr [$ m] <$ arr [$ m + 1]) { $ Temp = $ arr [$ m]; $ Arr [$ m] = $ arr [$ m + 1]; $ Arr [$ m + 1] = $ temp; } // Echo $ arr [$ m].' '; } } // Output the sorted result Var_dump ($ arr ); // Bubble sequence For ($ x = 0; $ x <$ num-1; $ x ++ ){ For ($ y = 0; $ y <$ num-1; $ y ++ ){ If ($ arr [$ y]> $ arr [$ y + 1]) { $ Temp = $ arr [$ y]; $ Arr [$ y] = $ arr [$ y + 1]; $ Arr [$ y + 1] = $ temp; } } } // Output the sorted result Var_dump ($ arr ); // Binary search Function dichotomy ($ array, $ k, $ low = 0, $ high = 0 ){ If (count ($ array )! = 0 & $ high = 0 ){ $ High = count ($ array ); } If ($ low <= $ high ){ $ Mid = intval ($ low + $ high)/2 ); If ($ array [$ mid] === k ){ Return $ mid; } Elseif ($ k <$ array [$ mid]) { Return dichotomy ($ array, $ k, $ low = 0, $ mid-1 ); } Else { Return dichotomy ($ array, $ k, $ mid + 1, $ high ); } } Else { Return false; } } // Output the search result Echo dichotomy ($ arr, 23 ); |
Today, I briefly studied the most common sorting and binary lookup of the bubble method, and wrote a simple case to enhance my learning of php.
It also hopes to provide a little help for future php learners.
Bytes. Code...