Advertisement
Guest User

Untitled

a guest
Oct 7th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.25 KB | None | 0 0
  1. let testDestructiveSort (sort : int [] -> unit) =
  2.    let test input expected =
  3.       let result = input |> List.toArray
  4.       sort result
  5.       let res = result |> List.ofArray
  6.       if res = expected then
  7.          printfn "[ OK ] sort %A -> %A" input expected
  8.       else
  9.          printfn "[FAIL] sort %A -> %A != %A" input res expected
  10.    test [] []
  11.    test [1] [1]
  12.    test [1; 2] [1; 2]
  13.    test [2; 1] [1; 2]
  14.    test [1; 3; 2] [1; 2; 3]
  15.    test [2; 1; 1] [1; 1; 2]
  16.    test [5; 4; 3; 2; 1] [1; 2; 3; 4; 5]
  17.  
  18. let arraySortD (arr : int []) =
  19.    let rnd = new System.Random()
  20.    let partition lo hi =
  21.          let p = rnd.Next(lo, hi)
  22.          let pivot = arr.[p]
  23.          let mutable i = lo - 1
  24.          let mutable j = hi + 1
  25.          while i < j do
  26.             i <- i + 1
  27.             while arr.[i] < pivot do
  28.                i <- i + 1
  29.             j <- j - 1
  30.             while arr.[j] > pivot do
  31.                j <- j - 1
  32.             if i < j then
  33.                let tmp = arr.[i]
  34.                arr.[i] <- arr.[j]
  35.                arr.[j] <- tmp
  36.          j
  37.    let rec qsort lo hi =
  38.       if lo < hi then
  39.          let p = partition lo hi
  40.          qsort lo p
  41.          qsort (p + 1) hi
  42.    qsort 0 (arr.Length - 1)
  43.  
  44. testDestructiveSort arraySortD
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement