Search code examples
javac#phppythonselection-sort

Sort 2D array with selection-sort method and write the result to the file


I have a task to do and I am a little stuck. I have to order some arrays from a file with 'selection sort' method and write the solution to the end of the file. For example:

file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99

is given. After sorting I should have something like that:

file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99
----sorted----
1 3 6 8 9 12
1 3 8 22
5 19 61 78 99

I have to mention that I have to do it in PHP, Java, C# and Python. I started coding it in PHP but I'm a little stuck. My code looks like this:

<?php

function selectionSort(array $array) {
    $length = count($array);
    for($i = 0; $i < $length; $i ++) {
        $min = $i;
        for($j = $i + 1; $j < $length; $j ++) {
            if ($array[$j] < $array[$min]) {
                $min = $j;
            }
        }
        $tmp = $array[$min];
        $array[$min] = $array[$i];
        $array[$i] = $tmp;
    }
    return $array;
}

//CREATE ARRAYS FROM FILE LINES:
$file_handle = fopen("fisier.txt", "r+");

while (!feof($file_handle) ) {

    $line_of_text = fgets($file_handle);
    $parts = explode(' ', $line_of_text);
    $parts_sorted = selectionSort($parts);
     for ($n=0; $n<count($parts_sorted); $n++){
        echo $parts_sorted[$n]." ";
    }

    echo "<br>";

}
fclose($file_handle);

The problem here is that it doesn't sort well, I mean my txt file is

9 12 5 4 13 8
3 7 12 44 22 4 13
70 1 12 55 34
22 13 7 50 3 1 9 14 27 77
56 2 9 45 35 12 7 63

and the result from the php code is

4 5 8 9 12 13
13 3 4 7 12 22 44
1 12 34 55 70
1 3 7 77 9 13 14 22 27 50
2 7 9 12 35 45 56 63 

which is not a good sort. Can you tell why? Do you know what should I do next to write the sorted arrays to the end of the file? And a little help for java,c# and python would be great. Sorry for the long post but I am a noob here. Thank you!


Solution

  • fgets() returns the linefeed/carriage-return character that ends the line So you're not comparing 13 to something but 13\r\n or 13\n or ....

    You can either do something like

    $line_of_text = trim(fgets($file_handle));
    

    to get rid of any leading/trailing whitespace of the line read from the file and/or

    $parts = array_map('intval', explode(' ', $line_of_text));
    

    to convert every element to an integer.

    (In case all elements are within the value range of a php integer, I advise using the array_map/intval thingy as the comparision of numers as number is apparently what you want. Otherwise you might be interested in strnatcmp() as your comparision function instead of the < operator)