Any simpler way to implement non-in-place selection sort in OCaml?

不羁岁月 提交于 2019-12-02 07:49:58

Edit: Here's a much better implementation: http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort#OCaml

here's my own crappier implementation

(* 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 [] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!