What is the most elegant way of bubble-sorting in F#?
UPDATE
As pointed out in one of the answers, bubble sorting isn't efficient in a functional language to begin with. A humourously-cynical commenter also pointed out that bubble sorting is only appropriate when the list is small and it's almost sorted anyway.
However, I'm curious to see how a clever bubble-sort can be written in F#, since I've done bubble sorts in C#, C++, and Java EE in the past, and since I'm an F# newbie.
Number of swaps reduced than bubble sort. For smaller values of N, insertion sort performs efficiently like other quadratic sorting algorithms.
The bubble sort is made up of only a few lines of code. With a best-case running time complexity of O(n), the bubble sort is helpful in determining whether or not a list is sorted. Other sorting methods frequently cycle through their entire sorting sequence, taking O(n2) or O(n log n) time to complete.
Insertion sort is an efficient sorting algorithm than selection and bubble sort? The average case time complexity of the insertion sort is closer to the worst-case time complexity i.e. O(n²). The above pseudo-code sort the array in increasing order.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
using bubble sort in a functional language isn't very efficient, because the implementation has to reverse the list many times (and this can't be really implemented very efficiently for immutable lists).
Anyway, the example from Erlang can be rewritten to F# like this:
let sort l =
let rec sortUtil acc rev l =
match l, rev with
| [], true -> acc |> List.rev
| [], false -> acc |> List.rev |> sortUtil [] true
| x::y::tl, _ when x > y -> sortUtil (y::acc) false (x::tl)
| hd::tl, _ -> sortUtil (hd::acc) rev tl
sortUtil [] true l
On the other side, you can implement the same algorithm using mutable arrays. This will be more efficient and in F# you can work with arrays too if you want. The following function creates a copy of the array and sorts it.
let sort (arr:'a[]) =
let arr = arr |> Array.copy
let swap i j = let tmp = arr.[i] in arr.[i] <- arr.[j]; arr.[j] <- tmp
for i = arr.Length - 1 downto 0 do
for j = 1 to i do
if (arr.[j - 1] > arr.[j]) then swap (j-1) j
arr
Tomas
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With