We learned the bubble sort and binary search sort algorithms in junior high school. I will introduce the examples of the bubble sort and binary search in PHP.
We learned the bubble sort and binary search sort algorithms in junior high school. next I will introduce the PHP bubble sort and binary query examples.
Bubble sort to give a 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, I also hope to provide some help to php learners in the future.