Running Time of Algorithms

  • + 0 comments

    Here's my PHP solution:

    function runningTime($arr) {
        // Write your code here
        $total = 0;
        
        for ($i=0; $i < count($arr)-1; $i++) {
            $temp = 0;
            for ($j=$i+1; $j < count($arr); $j++) {
                if ($arr[$j] < $arr[$i]) {
                    $temp = $arr[$j];
                    // delete array $arr[$j]
                    unset($arr[$j]);
                    
                    // insert in front of array
                    array_splice( $arr, $i, 0, $temp );
                    
                    // count step
                    $total = $total + ($j - $i);
                    
                    // re-index array
                    $arr = array_values($arr);
                }
            }
        } 
        return $total;
    }