Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active August 11, 2016 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/84b30c9f5ab8f95e2727cd8c9942c17f to your computer and use it in GitHub Desktop.
Save jackmott/84b30c9f5ab8f95e2727cd8c9942c17f to your computer and use it in GitHub Desktop.
Faster Array.partition for F#
let arrayPartition f (array: _[]) =
checkNonNull array
//Hold both arrays in one of exact length
let res = Array.zeroCreate array.Length
let mutable upCount = 0
let mutable downCount = array.Length-1
for i = 0 to array.Length-1 do
let x = array.[i]
if f x then
res.[upCount] <- x
upCount <- upCount + 1
else
res.[downCount] <- x
downCount <- downCount - 1
//First array is just a subset
let res1 = Array.sub res 0 upCount
//Second array needs to be reversed
let res2 = Array.zeroCreate (array.Length - upCount)
downCount <- array.Length-1
for i = 0 to res2.Length-1 do
res2.[i] <- res.[downCount]
downCount <- downCount - 1
res1,res2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment