【PHP】排序演算法 - 選擇演算法 ( Selection Sort )

class ConsecutiveTestCases extends TestCase
{
    private function revTest($actual, $expected) {
        $this->assertEquals($expected, $actual);
    }
    public function testBasics() {
        $this->revTest(longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2), "abigailtheta");
        $this->revTest(longestConsec(["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"], 1), "oocccffuucccjjjkkkjyyyeehh");
        $this->revTest(longestConsec([], 3), "");
    }
}
function longestConsec($strarr, $k) {
    // your code
    if($k > count($strarr) || $k <= 0 || count($strarr) === 0) return '';
    // selection sort
    for($i = 0; $i < count($strarr) ; $i ++){
        $maxLoc = $i;
        // next arr
        for($j = $i + 1; $j < count($strarr); $j ++){
            if( strlen($strarr[$j]) > strlen($strarr[$maxLoc]) ){
                $maxLoc = $j;
            }
        }    
        //exchange arr
        if($i != $maxLoc){
            $tmp = $strarr[$i];
            $strarr[$i] = $strarr[$maxLoc];
            $strarr[$maxLoc] = $tmp;
        }
    }
    //combine string
    $returnString = '';
    for($i = 0 ; $i < $k ; $i ++){
      $returnString .= $strarr[$i];
    }
    return $returnString;
}

參考 http://notepad.yehyeh.net/Content/Algorithm/Sort/Selection/1.php

留言