I want to sort a slice of an array, but the following code doesn't work as expected:
let arr = [|2; 8; 4; 1|]
Array.sortInPlace arr
printfn "%A" arr //1,2,4,8
let mutable arr2 = [|2; 8; 4; 1|]
Array.sortInPlace arr2.[1..]
printfn "%A" arr2.[1..] //8,4,1. Expected: 1,4,8
printfn "%A" arr2 //2,8,4,1. Expected: 2,1,4,8
The mutable keyword has no effect one way or the other.
How do I sort a continuous section of an array in-place in F#?
You can use System.MemoryExtensions to sort Spans. Spans is a view around existing data that won't create any copies.
open System
let ar = [|2; 8; 4; 1|]
ar.AsSpan().Slice(1).Sort() // taking span of array, slicing from 1 index and sort remaining elements
printfn "%A" ar // [|2; 1; 4; 8|]
Note: this is supported only from net5
Solved by using System.Array.Sort. Using C# array instead of F#, but good enough I think.
let arr = [|2; 8; 1; 4|]
System.Array.Sort(arr, 1, arr.Length-1)
printfn "%A" arr //[|2; 1; 4; 8|]
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