Facebook Twitter LinkedIn E-mail
magnify
Home F# F# 插入排序 和归并排序
formats

F# 插入排序 和归并排序

Published on 2016 年 09 月 04 日

插入排序 insertSort

let insertSort array =
    let length = Array.length array
    for i in [1..(length-1)] do
        let key = array.[i]
        //insert key to sub array[0..i-1]
        let mutable j = i-1
        while (j>=0 && array.[j]>key) do
            array.[j+1] <- array.[j]
            j <- j-1
        array.[j+1]<-key

let a=[|6;7;1;3;2;9;8;18;18;12|]

a |> insertSort

归并排序 mergesort


let merge array lo mid hi =
    let mutable i = lo
    let mutable j = mid
    let length = Array.length array
    let tempArray = Array.create length 0
    let mutable index =0
    while (i<mid && j<hi) do
        if array.[i]<array.[j] then
            tempArray.[index]<-array.[i]
            i<-i+1
            index<-index+1
        if array.[i]>=array.[j] then
            tempArray.[index]< -array.[j]
            j<-j+1
            index<-index+1

    //check if there's any remaining let
    if i<mid then 
        for k in [i .. (mid-1)] do
            tempArray.[index] <- array.[k]
            index<-index+1

    if j<hi then
        for k in [j .. (hi-1)] do
            tempArray.[index] <- array.[k]
            index<-index+1

    for i in [lo..(hi-1)] do
        array.[i] <- tempArray.[i-lo]

 
let rec mergeSort' array lo hi =
    let length = hi - lo
    if hi>1 + lo then
        let mid = (hi+lo)/2
        mergeSort' array lo mid
        mergeSort' array mid hi
        merge  array lo mid hi


let mergeSort array =
    mergeSort' array 0 (Array.length array)



let array =[|4;1;5;6;7;8;13;19;12|]

array |> mergeSort

 
Tags: ,
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn