Sorting algorithms/Bubble sort: Difference between revisions
Content deleted Content added
→{{header|JavaScript}}: Added real version for two js implementation. |
added ocaml |
||
Line 412: | Line 412: | ||
myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1) |
myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1) |
||
myArr = bubbleSort myArr |
myArr = bubbleSort myArr |
||
=={{header|OCaml}}== |
|||
Like the Haskell versions above: |
|||
This version checks for changes in a separate step for simplicity. |
|||
let rec bsort s = |
|||
let rec _bsort = function |
|||
| x :: x2 :: xs when x > x2 -> |
|||
x2 :: _bsort (x :: xs) |
|||
| x :: x2 :: xs -> |
|||
x :: _bsort (x2 :: xs) |
|||
| s -> s |
|||
in |
|||
let t = _bsort s in |
|||
if t = s then t |
|||
else bsort t |
|||
This version uses the polymorphic <tt>option</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>'a list -> 'a list option</tt>.) It is slightly faster than the previous one. |
|||
let rec bsort s = |
|||
let rec _bsort = function |
|||
| x :: x2 :: xs when x > x2 -> begin |
|||
match _bsort (x :: xs) with |
|||
| None -> Some (x2 :: x :: xs) |
|||
| Some xs2 -> Some (x2 :: xs2) |
|||
end |
|||
| x :: x2 :: xs -> begin |
|||
match _bsort (x2 :: xs) with |
|||
| None -> None |
|||
| Some xs2 -> Some (x :: xs2) |
|||
end |
|||
| _ -> None |
|||
in |
|||
match _bsort s with |
|||
| None -> s |
|||
| Some s2 -> bsort s2 |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |