user9665770
user9665770

Reputation:

PHP Selection sort for semi-numeric array not actually sorting

I have an array in PHP:

(Name, level, score)
array(5) { 
    [0]=> string(28) "Mr Kowalchuk,9,4000000000" 
    [1]=> string(12) "Test Boy    ,0,0" 
    [2]=> string(16) "Mr Test     ,2,150" 
    [3]=> string(16) "Rutherford  ,6,490" 
    [4]=> string(18) "Isaac Newton,3,235" 
}

I am wishing to sort this array by the LAST column, the Score column. The code I am using is a slightly modified version of selection sort that allows me to sort by extracting the score parameter and using that value instead of the whole text (you can't sort by text in this case).

<?php
function getScoreValue($row) {
    return (int)(explode(",", $row)[2]);
}

function minIndex($ma, $mi, $mj) {
    if ($mi == $mj) {
        return $mi;
    }
    $k = minIndex($ma, $mi + 1, $mj);
    if (getScoreValue($ma[$mi]) < getScoreValue($ma[$k])) {
        return $mi;
    } else {
        return $k;
    }
}

function recursiveSelectionSort($ma, $mn, $mindex = 0) {
    ##echo 'Running...<br>';
    if ($mindex == $mn) {
        return -1;
    }
    $k = minIndex($ma, $mindex, $mn - 1);
    if ($k != $mindex) {
        $temp = $ma[$k];
        $ma[$k] = $ma[$mindex];
        $ma[$mindex] = $temp;
    }
    recursiveSelectionSort($ma, $mn, $mindex + 1);
}

I call my function with

recursiveSelectionSort($myarray, sizeof($mayarry));

However, using PHP's var_dump, it shows that the array stays the same and does not change. Any idea why this is happening and what I could do to fix it?

Upvotes: 1

Views: 58

Answers (1)

sumit
sumit

Reputation: 15464

You do not need any recursion here. This is my idea. Check the comment for explanation

$a1=array( 
    "Mr Kowalchuk,9,4000000000", 
    "Test Boy    ,0,0" ,
    "Mr Test     ,2,150", 
    "Rutherford  ,6,490" ,
    "Isaac Newton,3,235" ,
    );

//explode entires with comma to make nested array
$a2=array_map(function ($a) { return explode(",",$a); }, $a1);
//sort based on inner key 
usort($a2, function ($a, $b) { return $a[2] - $b[2]; });
//implode back with comma to make it 1d array
$a3=array_map(function ($a) { return implode(",",$a); }, $a2);
echo "<pre>";
print_r($a3);

output

Array
(
    [0] => Test Boy    ,0,0
    [1] => Mr Test     ,2,150
    [2] => Isaac Newton,3,235
    [3] => Rutherford  ,6,490
    [4] => Mr Kowalchuk,9,4000000000
)

Upvotes: 1

Related Questions