F# 插入排序 和归并排序

栏目: ASP.NET · 发布时间: 9年前

内容简介:F# 插入排序 和归并排序

插入排序 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 length>1 then
        let mid = max ((hi - lo)/2) (lo+1)
        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

以上所述就是小编给大家介绍的《F# 插入排序 和归并排序》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

The Intersectional Internet

The Intersectional Internet

Safiya Umoja Noble、Brendesha M. Tynes / Peter Lang Publishing / 2016

From race, sex, class, and culture, the multidisciplinary field of Internet studies needs theoretical and methodological approaches that allow us to question the organization of social relations that ......一起来看看 《The Intersectional Internet》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具