-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.fsx
77 lines (67 loc) · 2.52 KB
/
BubbleSort.fsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// https://en.wikipedia.org/wiki/Bubble_sort
let rec bubbleSort (listToSort: 'A list) : 'A list =
let rec bs (listBegin:'A list) (curr:'A) (listEnd:'A list) : 'A list =
match listEnd with
| [] -> (curr::listBegin) |> List.rev
| next::le ->
if curr < next
then bs (curr::listBegin) next le
else bs (next::listBegin) curr le
match listToSort with
| [] -> listToSort
| first::rest ->
let newList = bs [] first rest
if listToSort <> newList
then (bubbleSort newList)
else newList
/// skip last element
let bubbleSort2 (listToSort: 'A list) : 'A list =
let rec bs (listBegin:'A list) (listEnd:'A list) (listStart:'A list): 'A list =
match listBegin, listEnd with
| [], [] -> listStart |> List.rev
| last::lb, [] ->
if (listBegin |> List.rev) = listStart
then listBegin
else
let lb = lb |> List.rev
last :: (bs [] lb lb)
| [], next::le -> bs [next] le listStart
| first::lb, next::le ->
if first > next
then bs (first::next::lb) le listStart
else bs (next::first::lb) le listStart
bs [] listToSort listToSort |> List.rev
/// swap two elements in mutable array
let private swap (a:int) (b:int) (array:'A array) : unit =
let value = array[a]
array[a] <- array[b]
array[b] <- value
// let private swap (a:int) (b:int) (array:int array) : unit =
// array[a] <- array[a] ^^^ array[b]
// array[b] <- array[a] ^^^ array[b]
// array[a] <- array[a] ^^^ array[b]
/// imperative style with mutable array
let bubbleSort3 (listToSort:'A seq) : 'A array =
let listToSort = listToSort |> Seq.toArray
let mutable n = listToSort |> Seq.length
while n > 1 do
let mutable newn = 0
for i = 1 to (n-1) do
if listToSort[i-1] > listToSort[i] then
listToSort |> swap (i-1) i
newn <- i
n <- newn
listToSort
/// rec loop with mutable array (w/o other mutables)
let bubbleSort4 (listToSort:'A seq) : 'A array =
let listToSort = listToSort |> Seq.toArray
let rec loop n i newn =
if n > 1 then
if i < n then
if listToSort[i-1] > listToSort[i] then
listToSort |> swap (i-1) i
loop n (i+1) i
else loop n (i+1) newn
else loop newn 1 0
loop (listToSort |> Seq.length) 1 0
listToSort