Sanchime.Learn/Algrithms/Sorts/BubbleSort.fs

16 lines
480 B
Forth

namespace Sanchime.Algrithm.Sort
[<AutoOpen>]
module Bubble =
let rec bsort sorted = function
| [] -> []
| [x] -> [x]
| xs ->
let sxs = xs |> swap sorted
if sxs = xs then xs else sxs |> bsort sorted
// 比较相邻元素,反复交换
and swap sorted = function
| [] -> []
| [x] -> [x]
| x::y::xs ->
if sorted x y then x::(y::xs |> swap sorted) else y::(x::xs |> swap sorted)