函数式编程-在OCaml中实现非原地选择排序的任何更简单的方法



我在OCaml中实现了选择排序的non-in-place版本。


let sort compare_fun l = 
    let rec find_min l' min_l origin_l =
      match l' with
    | [] -> 
      if min_l = [] then (min_l, l')
      else 
        let min = List.hd min_l 
        in 
        (min_l, List.filter (fun x -> if x != min then true else false)  origin_l)
    | x::tl -> 
      if min_l = [] then
        find_min tl [x] origin_l
      else 
        let c = compare_fun (List.hd min_l) x
        in 
        if c = 1 then 
          find_min tl [x] origin_l
        else if c = 0 then
          find_min tl (min_l @ [x]) origin_l
        else 
          find_min tl min_l origin_l
    in 
    let rec insert_min l' new_l =
      match l' with
    | [] -> new_l
    | _ -> 
      let (min_l, rest) = find_min l' [] l'
      in 
      insert_min rest (new_l @ min_l)
    in 
    insert_min l [];;

我的想法是,在列表中,每次我找到最小项目的列表(在值重复的情况下)并将该min list添加到结果列表中,然后在列表的其余部分中重做finding_min。

我使用List.filter来过滤掉min_list,所以得到的列表将是下一个find_min的列表。

我发现我的实现相当复杂,而且比选择排序的Java就地版本复杂得多

有什么改进的建议吗?

Edit:这里有一个更好的实现:http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort#OCaml

这是我自己糟糕的实现

(* partial function - bad habit, don't do this. *)
let smallest (x::xs) = List.fold_right (fun e acc -> min e acc) xs x
let remove l y =
  let rec loop acc = function
    | [] -> raise Not_found
    | x::xs -> if y = x then (List.rev acc) @ xs else loop (x::acc) xs
  in loop [] l
let selection_sort = 
  let rec loop acc = function
    | [] -> List.rev acc
    | xs -> 
        let small = smallest xs in
        let rest = remove xs small in
        loop (small::acc) rest
  in loop [] 

最新更新