PHP bubble sorting and binary searching for instances

Source: Internet
Author: User
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:

  1. For ($ I = 0; $ I <$ num-1; $ I ++ ){
  2. For ($ m = 0; $ m <$ num-1; $ m ++ ){
  3. If ($ arr [$ m] <$ arr [$ m + 1]) {
  4. $ Temp = $ arr [$ m];
  5. $ Arr [$ m] = $ arr [$ m + 1];
  6. $ Arr [$ m + 1] = $ temp;
  7. }
  8. // Echo $ arr [$ m].'
    ';
  9. }
  10. }
  11. // Output the sorted result
  12. Var_dump ($ arr );
  13. // Bubble sequence
  14. For ($ x = 0; $ x <$ num-1; $ x ++ ){
  15. For ($ y = 0; $ y <$ num-1; $ y ++ ){
  16. If ($ arr [$ y]> $ arr [$ y + 1]) {
  17. $ Temp = $ arr [$ y];
  18. $ Arr [$ y] = $ arr [$ y + 1];
  19. $ Arr [$ y + 1] = $ temp;
  20. }
  21. }
  22. }
  23. // Output the sorted result
  24. Var_dump ($ arr );
  25. // Binary search
  26. Function dichotomy ($ array, $ k, $ low = 0, $ high = 0 ){
  27. If (count ($ array )! = 0 & $ high = 0 ){
  28. $ High = count ($ array );
  29. }
  30. If ($ low <= $ high ){
  31. $ Mid = intval ($ low + $ high)/2 );
  32. If ($ array [$ mid] === k ){
  33. Return $ mid;
  34. } Elseif ($ k <$ array [$ mid]) {
  35. Return dichotomy ($ array, $ k, $ low = 0, $ mid-1 );
  36. } Else {
  37. Return dichotomy ($ array, $ k, $ mid + 1, $ high );
  38. }
  39. } Else {
  40. Return false;
  41. }
  42. }
  43. // Output the search result
  44. 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.