F#实现的归并排序

F#实现的归并排序

 

//此算法只是原理,不能真正应用
open System
printfn "dsfsadsf" 
let Merge(x,y)=
     (x@y)|>List.sort

//自上而下深度优先

let rec MergeSortUp (sortList:List<int>)=
    match sortList with
    |[]->[]
    |[x]->[x]
    |xs->
        let k=xs.Length/2
        let a=List.toSeq(xs)|>Seq.take(k)
        let b=List.toSeq(xs)|>Seq.filter(fun e->not(a|>Seq.exists(fun s->s=e)))
        Merge(MergeSortUp(a|>Seq.toList),MergeSortUp(b|>Seq.toList))


let test=MergeSortUp([2;3;9;8;7;1])
//自底向上//不好用得修改

let rec MergePairs(part,k)=
    match part with
    |[x]->[x]
    |(l1::l2::ls)-> 
        printf "%A__%A" l1 l2
        if k%2=1 then l1::l2::ls
        else 
           MergePairs((Merge([l1],[l2])@ls),k/2)
    |_->[]
    
let rec Sorting(lx:List<int>,ls:List<int>,k:int)=
    match lx with
    |[]->MergePairs(ls,0)
    |(x::xs)->Sorting(xs,MergePairs(x::ls,k+1),k+1)
let MergeSortDown xs=Sorting(xs,[],0)
MergeSortDown([2;3;9;8;7;1])



 

你可能感兴趣的:(算法,F#)