两个两部分函数的时间复杂度O()

时间:2015-10-20 11:41:16

标签: f#

这两种算法的时间复杂度是多少?

let rec fol f a = function
      | []    -> a
      | x::xs -> fol f (f a x) xs;;

let mergelist xs = List.fol (@) [] xs

let rec folB f xs a =
      match xs with
      | []    -> a
      | y::ys -> f y (folB f ys a);;

let mergelist2 xs = List.folB (@) xs []

我怎么能自己测试呢?

应该返回类似

的内容
mergelist [[1;2];[];[3];[4;5;6]];;
  val it : int list = [1; 2; 3; 4; 5; 6]

1 个答案:

答案 0 :(得分:4)

以下是一个快速简洁的片段,介绍如何将这两项操作与n长度3列表进行比较:

let rec fol f a = function
      | []    -> a
      | x::xs -> fol f (f a x) xs;;

let rec folB f xs a =
      match xs with
      | []    -> a
      | y::ys -> f y (folB f ys a);;

let compareThemFor n =
    let testList = List.replicate n [1;2;3]
    let count = ref 0

    let myCons x xs =
        incr count
        x :: xs

    let myApp ys =
        List.foldBack myCons ys

    let mergelist = fol myApp []
    mergelist testList |> ignore
    let countA = !count

    count := 0
    let mergelist2 xs = folB myApp xs []
    mergelist2 testList |> ignore
    let countB = !count

    (countA, countB)

这就是你将得到的:

> compareThemFor 2;;
val it : int * int = (3, 6)
> compareThemFor 3;;
val it : int * int = (9, 9)
> compareThemFor 4;;
val it : int * int = (18, 12)
> compareThemFor 5;;
val it : int * int = (30, 15)
> compareThemFor 6;;
val it : int * int = (45, 18)

你可以看到第二个更好,我希望上面的评论可以帮助你理解原因。

以下是n=3的{​​{1}}版本:

mergelist

请注意,您多次添加mergelist [[1;2;3];[3;4;5];[6;7;8]] { second case in `fol` with `x=[1;2;3]` and `xs=[[3;4;5];[6;7;8]]` } = fol (@) ([] @ [1;2;3]) [[3;4;5];[6;7;8]] // one @ of 0 elements = 0 operations { second case in `fol` with `x=[3;4;5]` and `xs=[[6;7;8]]` } = fol (@) ([1;2;3] @ [3;4;5]) [[6;7;8]] // one @ of 3 elements = 3 operations { second case in `fol` with `x=[6;7;8]` and `xs=[]` } = fol (@) ([1;2;3;3;4;5] @ [6;7;8]) [] // one @ of 6 elements = 6 operations { first case } = [1;2;3;3;4;5;6;7;8] // 0+3+(3+3)=9 Operations Total 次...