Thursday, 8 March 2018

Bubble Sort Program In PHP

demo.html
<html>
<body>
<form name="form1" id="form1" method="post" action="bubble1.php">
    <h1>Bubble Sort</h1>
    <h3>Submit the numbers</h3>
            <label>Number 1<input type="text" name="bsort_val[]" id="bsort_val1" size="10" maxlength="10"></label><br>
            <label>Number 2<input type="text" name="bsort_val[]" id="bsort_val2" size="10" maxlength="10"></label><br>
            <label>Number 3<input type="text" name="bsort_val[]" id="bsort_val3" size="10" maxlength="10"></label><br>
            <label>Number 4<input type="text" name="bsort_val[]" id="bsort_val4" size="10" maxlength="10"></label><br>
            <label>Number 5<input type="text" name="bsort_val[]" id="bsort_val5" size="10" maxlength="10"></label><br>
            <input type="submit" value="Bubble Sort" id="submitbtn">
</form>
</body>
</html>

bubble1.php
<?php
        function bubbleSort(array $arr)
        {
            $n = sizeof($arr);  
            for ($i = 1; $i < $n; $i++) {
                $flag = false;
                for ($j = $n - 1; $j >= $i; $j--) {
                    if($arr[$j-1] > $arr[$j]) {
                        $tmp = $arr[$j - 1];
                        $arr[$j - 1] = $arr[$j];
                        $arr[$j] = $tmp;
                        $flag = true;
                    }
                }
                if (!$flag) {
                    break;
                }
            }

      return $arr;
        }

        // Example:
        if (isset($_POST['bsort_val']) && !empty($_POST['bsort_val']))
                   {
            echo '<pre>';
            echo 'Before sort: ';
            print_r($_POST['bsort_val']);
            echo '<br>****************<br>';
            echo 'After sort:' ;
            print_r(bubbleSort($_POST['bsort_val']));
            echo '</pre>';
        }
        ?>
 Output:

Bubble Sort


Submit the numbers







Before sort: Array
(
    [0] => 78
    [1] => 90
    [2] => 4
    [3] => 45
    [4] => 566
)

****************
After sort:Array
(
    [0] => 4
    [1] => 45
    [2] => 78
    [3] => 90
    [4] => 566
)

No comments:

Post a Comment

Global Infrastructure and its components in AWS

You may operate your workloads wherever and however you choose with the AWS Global Infrastructure, and you'll use the same network, cont...