Skip to content

Instantly share code, notes, and snippets.

@samhavens
Created May 7, 2014 06:18
Show Gist options
  • Save samhavens/ffcf8cbe8cd308e7b95a to your computer and use it in GitHub Desktop.
Save samhavens/ffcf8cbe8cd308e7b95a to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Merge Sort with Inversion Count Using PHP</title>
</head>
<body>
<form action="openfile.php" method="post">
Name of input file: <input type="text" name="name"><br>
<input type="submit">
</form>
<?php
if (!empty($_POST["name"])) {
$a = [];
#put test data into array $a
$file = fopen($_POST["name"], "r");
while(!feof($file)) {
$a[] = (int) fgets($file);
}
fclose($file);
echo "Input array: <br>";
foreach ($a as $key => $value) {
echo "{$value} <br>";
}
echo "<br>";
function merge_sort($array) {
$left = [];
$right = [];
global $inversion_count;
$inversion_count = 0;
#This is the base case
if (count($array) == 1) {
return $array;
echo "this many times";
}
#This is the n > 1 case
else {
$middle = (int) round(count($array)/2);
#echo "<br> {$middle} <br>";
$left = array_slice($array, 0, $middle);
$right = array_slice($array, $middle);
$array = [];
$left = merge_sort($left);
$right = merge_sort($right);
while (!empty($left) && !empty($right)) {
if ($left[0] < $right[0]) {
$array[] = array_shift($left);
}
else {
$inversion_count += count($left);
$array[] = array_shift($right);
}
}
}
return array_merge($array, $left, $right);
}
echo "Sorted array: <br>";
foreach (merge_sort($a) as $key => $value) {
echo "{$value} <br>";
}
echo '<br>' . "Number of inversions: " . $inversion_count;
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment