Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.00 KB | None | 0 0
  1. module Partition
  2.  
  3.   use import int.Int
  4.   use import ref.Ref
  5.   use import array.Array
  6.  
  7.   predicate partitioned (a: array int) (pivot: int) (n: int) =
  8.       forall i:int. (0 <= i <= pivot ->  a[i] <= a[pivot]) /\
  9.                     (pivot < i < n -> a[i] > a[pivot])
  10.  
  11.   let partition (a: array int) (n: int)
  12.     requires { 2 <= n = length a }
  13.   = let lt = ref 0 in
  14.       let aux = ref a[0] in
  15.         a[0] <- a[n-1];
  16.         a[n-1] <- !aux;
  17.       for i = !lt to n - 2 do
  18.         invariant{0 <= !lt <= i /\
  19.             forall k: int. (0 <= k < !lt -> a[k] <= a[n-1]) /\
  20.                            (!lt <= k < i -> a[k] > a[n-1])}
  21.         if a[i] <= a[n-1] then
  22.           let aux = ref a[i] in
  23.             a[i] <- a[!lt];
  24.             a[!lt] <- !aux;
  25.             lt := !lt + 1;
  26.         else
  27.             assert{ !lt <= i /\ i < n-1 /\ a[i] > a[n-1]}
  28.       done;
  29.       let aux = ref a[n-1] in
  30.         a[n-1] <- a[!lt];
  31.         a[!lt] <- !aux;
  32.     assert{ partitioned a !lt n };
  33.     (a, lt)
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement