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.
Result of php executing
Full code of Bubble sort homework.php
- <?php
- function bubbleSort($arr)
- {
- $listCount = count($arr);
- for ($i = 0; $i < $listCount - 1; $i++) {
- $swapped = false;
- for ($j = 0; $j < $listCount - 1; $j++) {
- if ($arr[$j] > $arr[$j + 1]) {
- $temp = $arr[$j];
- $arr[$j] = $arr[$j + 1];
- $arr[$j + 1] = $temp;
- $swapped = true;
- }
- }
- if (!$swapped) {
- break;
- }
- }
- return $arr;
- }
- function binarySearch(Array $arr, $start, $end, $x){
- if ($end < $start){
- return false;
- }
- $mid = floor(($end + $start)/2);
- if ($arr[$mid] == $x) {
- return true;
- }
- elseif ($arr[$mid] > $x) {
- return binarySearch($arr, $start, $mid - 1, $x);
- }
- else {
- return binarySearch($arr, $mid + 1, $end, $x);
- }
- }
- function driver()
- {
- $arr = array( 5, 1, 4, 2, 8);
- $sortedList = bubbleSort($arr);
- $x = 2;
- var_dump($sortedList);
- if ( binarySearch($sortedList, 0, count($arr)-1, $x) == true) {
- echo "$x exists!";
- } else {
- echo "$x does not exist!";
- }
- }
- driver();
- ?>
File Description
- Bubble sort homework
- PHP Code
- 30 Apr-2022
- 1.13 Kb
You can Share it:
Latest PHP Pastes