Bubble sort homework - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of Bubble sort homework.php

  1. <?php
  2. function bubbleSort($arr)
  3. {
  4.     $listCount = count($arr);
  5.  
  6.     for ($i = 0; $i < $listCount - 1; $i++) {
  7.         $swapped = false;
  8.  
  9.         for ($j = 0; $j < $listCount - 1; $j++) {
  10.     
  11.             if ($arr[$j] > $arr[$j + 1]) {
  12.                 $temp = $arr[$j];
  13.                 $arr[$j] = $arr[$j + 1];
  14.                 $arr[$j + 1] = $temp;
  15.                 $swapped = true;
  16.             }
  17.         }
  18.  
  19.         if (!$swapped) {
  20.             break;
  21.         }
  22.     }
  23.     return $arr;
  24. }
  25.  
  26. function binarySearch(Array $arr, $start, $end, $x){
  27.     if ($end < $start){
  28.         return false;
  29.     }
  30.     $mid = floor(($end + $start)/2);
  31.     if ($arr[$mid] == $x) {
  32.         return true;
  33.     }
  34.     elseif ($arr[$mid] > $x) {
  35.         return binarySearch($arr, $start, $mid - 1, $x);
  36.     }
  37.     else {
  38.         return binarySearch($arr, $mid + 1, $end, $x);
  39.     }
  40. }
  41.  
  42.  
  43. function driver()
  44. {
  45.     $arr = array( 5, 1, 4, 2, 8);
  46.  
  47.     $sortedList = bubbleSort($arr);
  48.     $x = 2;
  49.  
  50.     var_dump($sortedList);
  51.     
  52.     
  53.     if ( binarySearch($sortedList, 0, count($arr)-1, $x) == true) {
  54.             echo  "$x exists!";
  55.     } else {
  56.             echo  "$x does not exist!";
  57.         }
  58. }
  59.  
  60. driver();
  61. ?>
  62.  
File Description
  • Bubble sort homework
  • PHP Code
  • 30 Apr-2022
  • 1.13 Kb
You can Share it: