Saturday, January 9, 2016

Merge Sort in PHP

A simple program that I wrote in PHP to sort a series of numbers Merge Sort algorithm.

 If you have some questions please send me an email at jakerpomperada@gmail.comand jakerpomperada@yahoo.com.  

My mobile number here in the Philippines is 09173084360.



Sample Program Output


Program Listing

<?php
error_reporting(0);

$a= $_POST['val_1'];
$b= $_POST['val_2'];
$c= $_POST['val_3'];
$d= $_POST['val_4'];
$e= $_POST['val_5']; 

 if(isset($_POST['clear']))
$a=""; $b=""; $c=""; $d=""; $e="";
$display_original="";  $process_results="";
}
?>
<html>
<head>
<title>Merge Sort in PHP</title>
<style>
body { font-family:arial;}
form { width: 400px; }
label { float: left; width: 95px; }
.clear { clear: both; height: 0; line-height: 0; }
.floatright { float: right; }
</style>
</head>
<body>
<h2>Merge Sort in PHP</h2>
<form  action="" method="post">
<label>Value No. 1 : </label> <input type="text" name="val_1" value="<?php echo $a; ?>" size="5" maxlength="5"  autofocus/><br/><br>
<label>Value No. 2 : </label> <input type="text" name="val_2" value="<?php echo $b; ?>" size="5" maxlength="5"/><br/><br>
<label>Value No. 3 : </label> <input type="text" name="val_3" value="<?php echo $c; ?>" size="5" maxlength="5"/><br/><br>
<label>Value No. 4 : </label> <input type="text" name="val_4" value="<?php echo $d; ?>"size="5" maxlength="5"/><br/><br>
<label>Value No. 5 : </label> <input type="text" name="val_5" value="<?php echo $e; ?>"size="5" maxlength="5"/><br/>
<br />
<input type="submit" value="Sort" name="bubble"/>
<input type="submit" value="Clear" name="clear" />
</form>

<?php
function Merge(&$data, $left, $mid, $right) {
$n1 = $mid - $left + 1;
$n2 = $right - $mid;

for ($i = 0; $i < $n1; $i++)
$L[$i] = $data[$left + $i];

for ($j = 0; $j < $n2; $j++)
$R[$j] = $data[$mid + 1 + $j];

$i = 0;
$j = 0;
$k = $left;

while ($i < $n1 && $j < $n2)
{
if ($L[$i] <= $R[$j])
{
$data[$k] = $L[$i];
$i++;
}
else
{
$data[$k] = $R[$j];
$j++;
}

$k++;
}

while ($i < $n1)
{
$data[$k] = $L[$i];
$i++;
$k++;
}

while ($j < $n2)
{
$data[$k] = $R[$j];
$j++;
$k++;
}

$L = null;
$R = null;
}

function MergeSort(&$data, $count) {
for ($currentSize = 1; $currentSize <= $count - 1; $currentSize = 2 * $currentSize)
{
for ($leftStart = 0; $leftStart < $count - 1; $leftStart += 2 * $currentSize)
{
$mid = $leftStart + $currentSize - 1;
$rightEnd = min($leftStart + 2 * $currentSize - 1, $count - 1);

Merge($data, $leftStart, $mid, $rightEnd);
}
}
}


if(isset($_POST['bubble']))


 $arr = array($a,$b,$c,$d,$e);
  $orig = implode(",", $arr); 

 MergeSort($arr,5);
 $final_sort = implode(",", $arr);

  $display_original =  "Original Values : " .$orig."<br><br>";
  $process_results  = "Sorted Values : " .$final_sort."<br>";
  
  echo $display_original;
  echo $process_results;

}

?>
</body>
</html>





No comments:

Post a Comment