Last active
August 11, 2016 03:55
-
-
Save jackmott/84b30c9f5ab8f95e2727cd8c9942c17f to your computer and use it in GitHub Desktop.
Faster Array.partition for F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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