【PHP】排序演算法 - 插入排序法 ( Insertion 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 '';
    // insertion sort
    for($i = 1; $i < count($strarr); $i ++ ){
                for($j = $i; $j > 0 && (strlen($strarr[$j]) > strlen($strarr[$j - 1]));$j--){
                        $tmp = $strarr[$j];
                        $strarr[$j] = $strarr[$j - 1];
                        $strarr[$j - 1] = $tmp;
                }
        };
    //combine string
    $returnString = '';
    for($i = 0 ; $i < $k ; $i ++){
      $returnString .= $strarr[$i];
    }
    return $returnString;
}

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

留言