Skip to content

Instantly share code, notes, and snippets.

@lachezar
Last active June 21, 2024 11:31
Show Gist options
  • Save lachezar/989f4564608af73b2e68541be948d595 to your computer and use it in GitHub Desktop.
Save lachezar/989f4564608af73b2e68541be948d595 to your computer and use it in GitHub Desktop.
Sorting with F#
// Inspired by Rock The JVM exercise video - https://youtu.be/hHMEMRGHmAI
let random = new System.Random()
let a: list<int> = [ for i in 1..1000 -> random.Next(1, 1000) ]
let rec insertSort (l: list<'a>) (comp: 'a -> 'a -> int) : list<'a> =
let rec insert (e: 'a) (l: list<'a>) : list<'a> =
if l.IsEmpty then [ e ]
else if comp e l.Head <= 0 then e :: l
else l.Head :: insert e l.Tail
if l.IsEmpty || l.Tail.IsEmpty then
l
else
insert l.Head <| insertSort l.Tail comp
let rec mergeSort (l: list<'a>) (comp: 'a -> 'a -> int) : list<'a> =
let rec merge (a: list<'a>) (b: list<'a>) : list<'a> =
if a.IsEmpty then
b
else if b.IsEmpty then
a
else if comp a.Head b.Head <= 0 then
a.Head :: merge a.Tail b
else
b.Head :: merge a b.Tail
if l.IsEmpty || l.Tail.IsEmpty then
l
else
let (a: 'a list, b: 'a list) = List.splitAt (l.Length / 2) l
merge <| mergeSort a comp <| mergeSort b comp
let rec quickSort (l: list<'a>) (comp: 'a -> 'a -> int) : list<'a> =
if l.IsEmpty then
l
else
let pivot: 'a = l.Head
let (a: list<'a>, b: list<'a>) =
List.partition (fun x -> comp x pivot < 0) <| l.Tail
quickSort a comp @ pivot :: quickSort b comp
let insertSortRes: list<int> = insertSort a compare
let mergeSortRes: list<int> = mergeSort a compare
let quickSortRes: list<int> = quickSort a compare
List.map (printfn "%A") [ insertSortRes; mergeSortRes; quickSortRes ]
printfn "Lists are equal: %b"
<| (List.compareWith compare insertSortRes mergeSortRes = 0
&& List.compareWith compare insertSortRes quickSortRes = 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment