Skip to content

Commit 43f325e

Browse files
authored
Merge pull request Al2Klimov#16 from Al2Klimov/feature/sort-#4
Allow to sort with the --numeric-sort param
2 parents d4dd131 + 20632fe commit 43f325e

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

sort.php

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,24 @@ function checkForNextLine($arr)
1313
return $arr;
1414
}
1515

16-
function bubbleSort($sort_array)
16+
function castToInt($firstNum, $secondNum)
17+
{
18+
return (int)$firstNum < (int)$secondNum;
19+
}
20+
21+
function checkForEquality($firstNum, $secondNum)
22+
{
23+
return $firstNum < $secondNum;
24+
}
25+
26+
function bubbleSort($sort_array, $checkEquality)
1727
{
1828
$array_indexes = count($sort_array);
1929
$sorted = false;
2030

2131
for ($i = 0; $i < $array_indexes; $i++) {
2232
for ($j = 0; $j < $array_indexes - $i - 1; $j++) {
23-
if ($sort_array[$j + 1] < $sort_array[$j]) {
33+
if ($checkEquality($sort_array[$j + 1], $sort_array[$j])) {
2434
$tmp = $sort_array[$j + 1];
2535
$sort_array[$j + 1] = $sort_array[$j];
2636
$sort_array[$j] = $tmp;
@@ -37,10 +47,18 @@ function bubbleSort($sort_array)
3747
return $sort_array;
3848
}
3949

40-
if($argc > 1 && substr($argv[1], 0, 1) !== '-') {
41-
$fileName = $argv[1];
50+
$optind = null;
51+
$options = getopt("n", [], $optind);
52+
if (key_exists("n", $options)) {
53+
$funcCallback = 'castToInt';
54+
} else {
55+
$funcCallback = 'checkForEquality';
56+
}
57+
58+
if(isset($argv[$optind])) {
59+
$fileName = $argv[$optind];
4260
} else {
4361
$fileName = 'php://stdin';
4462
}
4563

46-
echo implode("", bubbleSort(checkForNextLine(file($fileName))));
64+
echo implode("", bubbleSort(checkForNextLine(file($fileName)), $funcCallback));

0 commit comments

Comments
 (0)