【问题标题】:OCaml mergesort and timeOCaml 归并排序和时间
【发布时间】:2015-11-06 12:02:52
【问题描述】:

我在 ocaml 中创建了一个函数(合并排序),但是当我使用它时,列表是倒置的。

另外,我想计算系统进行计算所花费的时间,我该怎么做呢?

let rec merge l x y = match (x,y) with 
    | ([],_) -> y
    | (_,[]) -> x
    | (h1::t1, h2::t2) -> 
    if l h1 h2 
        then h1::(merge l t1 y)
        else h2::(merge l x t2);;

let rec split x y z = match x with
     | [] -> (y,z)
     | x::resto -> split resto z (x::y);;

let rec mergesort l x = match x with
    | ([] | _::[]) -> x
    | _ -> let (pri,seg) = split x [] [] 
    in merge l (mergesort l pri) (mergesort l seg);;

mergesort (>) [2;6;1;8];;
- : int list = [8; 6; 2; 1]

【问题讨论】:

    标签: sorting time merge ocaml


    【解决方案1】:

    if l h1 h2 行更改为if l h2 h1。比较两个子列表中的头元素的方式为您提供了一个倒排列表。

    另外,当您有多个递归函数相互调用时,我可以建议您使用以下语法:

    let rec merge cmp x y = match (x,y) with 
      | ([],_) -> y
      | (_,[]) -> x
      | (h1::t1, h2::t2) -> 
        if cmp h2 h1 
        then h1::(merge cmp t1 y)
        else h2::(merge cmp x t2)
    
    and split x y z = match x with
      | [] -> (y,z)
      | x::resto -> split resto z (x::y)
    
    and  mergesort cmp x = match x with
      | ([] | _::[]) -> x
      | _ -> let (pri,seg) = split x [] [] 
         in (merge cmp (mergesort cmp pri) (mergesort cmp seg));;
    

    要测量时间函数,你可以看看这里: Running time in Ocaml

    【讨论】:

      【解决方案2】:

      要对函数进行基准测试,请参阅 Core_Bench https://blogs.janestreet.com/core_bench-micro-benchmarking-for-ocaml/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-22
        • 2015-06-10
        • 2010-12-08
        • 2021-03-22
        • 2020-04-22
        • 1970-01-01
        • 2020-03-04
        相关资源
        最近更新 更多