-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.php
56 lines (46 loc) · 1.22 KB
/
sort.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
function checkAsInt($param, $value)
{
return (int)$param < (int)$value;
}
function checkAsStrings($param, $value)
{
return $param < $value;
}
function bubbleSort($arr, $funcCallback)
{
$checked = false;
for ($i = 1; $i < count($arr); $i++) {
for ($j = 0; $j < count($arr)-$i; $j++) {
if (strlen($arr[$j]) <= 1) {
unset($arr[$j]);
continue;
}
if ($funcCallback($arr[$j+1], $arr[$j])) {
$tempVal = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $tempVal;
$checked = true;
}
}
if ($checked === false) {
break;
}
}
return $arr;
}
$filename = 'php://stdin';
$funcCallback = 'checkAsStrings';
$optind = null;
$options = getopt('no:filename', [], $optind);
if ($argv[$optind]) {
$filename = $argv[$optind];
}
if(array_key_exists('n',$options)) {
$funcCallback = 'checkAsInt';
}
if ($options['o']) {
file_put_contents($options['o'], bubbleSort(file($filename), $funcCallback));
echo 'The following output is also saved in ' . $options['o'] . " file\n";
}
echo implode("", bubbleSort(file($filename), $funcCallback));