src/HOL/Imperative_HOL/ex/Imperative_Quicksort.thy
author huffman
Sun Mar 25 20:15:39 2012 +0200 (2012-03-25 ago)
changeset 47108 2a1953f0d20d
parent 44890 22f665a2e91c
child 50630 1ea90e8046dc
permissions -rw-r--r--
merged fork with new numeral representation (see NEWS)
     1 (*  Title:      HOL/Imperative_HOL/ex/Imperative_Quicksort.thy
     2     Author:     Lukas Bulwahn, TU Muenchen
     3 *)
     4 
     5 header {* An imperative implementation of Quicksort on arrays *}
     6 
     7 theory Imperative_Quicksort
     8 imports
     9   "~~/src/HOL/Imperative_HOL/Imperative_HOL"
    10   Subarray
    11   "~~/src/HOL/Library/Multiset"
    12   "~~/src/HOL/Library/Efficient_Nat"
    13 begin
    14 
    15 text {* We prove QuickSort correct in the Relational Calculus. *}
    16 
    17 definition swap :: "nat array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> unit Heap"
    18 where
    19   "swap arr i j =
    20      do {
    21        x \<leftarrow> Array.nth arr i;
    22        y \<leftarrow> Array.nth arr j;
    23        Array.upd i y arr;
    24        Array.upd j x arr;
    25        return ()
    26      }"
    27 
    28 lemma effect_swapI [effect_intros]:
    29   assumes "i < Array.length h a" "j < Array.length h a"
    30     "x = Array.get h a ! i" "y = Array.get h a ! j"
    31     "h' = Array.update a j x (Array.update a i y h)"
    32   shows "effect (swap a i j) h h' r"
    33   unfolding swap_def using assms by (auto intro!: effect_intros)
    34 
    35 lemma swap_permutes:
    36   assumes "effect (swap a i j) h h' rs"
    37   shows "multiset_of (Array.get h' a) 
    38   = multiset_of (Array.get h a)"
    39   using assms
    40   unfolding swap_def
    41   by (auto simp add: Array.length_def multiset_of_swap dest: sym [of _ "h'"] elim!: effect_bindE effect_nthE effect_returnE effect_updE)
    42 
    43 function part1 :: "nat array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat Heap"
    44 where
    45   "part1 a left right p = (
    46      if (right \<le> left) then return right
    47      else do {
    48        v \<leftarrow> Array.nth a left;
    49        (if (v \<le> p) then (part1 a (left + 1) right p)
    50                     else (do { swap a left right;
    51   part1 a left (right - 1) p }))
    52      })"
    53 by pat_completeness auto
    54 
    55 termination
    56 by (relation "measure (\<lambda>(_,l,r,_). r - l )") auto
    57 
    58 declare part1.simps[simp del]
    59 
    60 lemma part_permutes:
    61   assumes "effect (part1 a l r p) h h' rs"
    62   shows "multiset_of (Array.get h' a) 
    63   = multiset_of (Array.get h a)"
    64   using assms
    65 proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
    66   case (1 a l r p h h' rs)
    67   thus ?case
    68     unfolding part1.simps [of a l r p]
    69     by (elim effect_bindE effect_ifE effect_returnE effect_nthE) (auto simp add: swap_permutes)
    70 qed
    71 
    72 lemma part_returns_index_in_bounds:
    73   assumes "effect (part1 a l r p) h h' rs"
    74   assumes "l \<le> r"
    75   shows "l \<le> rs \<and> rs \<le> r"
    76 using assms
    77 proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
    78   case (1 a l r p h h' rs)
    79   note cr = `effect (part1 a l r p) h h' rs`
    80   show ?case
    81   proof (cases "r \<le> l")
    82     case True (* Terminating case *)
    83     with cr `l \<le> r` show ?thesis
    84       unfolding part1.simps[of a l r p]
    85       by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
    86   next
    87     case False (* recursive case *)
    88     note rec_condition = this
    89     let ?v = "Array.get h a ! l"
    90     show ?thesis
    91     proof (cases "?v \<le> p")
    92       case True
    93       with cr False
    94       have rec1: "effect (part1 a (l + 1) r p) h h' rs"
    95         unfolding part1.simps[of a l r p]
    96         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
    97       from rec_condition have "l + 1 \<le> r" by arith
    98       from 1(1)[OF rec_condition True rec1 `l + 1 \<le> r`]
    99       show ?thesis by simp
   100     next
   101       case False
   102       with rec_condition cr
   103       obtain h1 where swp: "effect (swap a l r) h h1 ()"
   104         and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
   105         unfolding part1.simps[of a l r p]
   106         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
   107       from rec_condition have "l \<le> r - 1" by arith
   108       from 1(2) [OF rec_condition False rec2 `l \<le> r - 1`] show ?thesis by fastforce
   109     qed
   110   qed
   111 qed
   112 
   113 lemma part_length_remains:
   114   assumes "effect (part1 a l r p) h h' rs"
   115   shows "Array.length h a = Array.length h' a"
   116 using assms
   117 proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
   118   case (1 a l r p h h' rs)
   119   note cr = `effect (part1 a l r p) h h' rs`
   120   
   121   show ?case
   122   proof (cases "r \<le> l")
   123     case True (* Terminating case *)
   124     with cr show ?thesis
   125       unfolding part1.simps[of a l r p]
   126       by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
   127   next
   128     case False (* recursive case *)
   129     with cr 1 show ?thesis
   130       unfolding part1.simps [of a l r p] swap_def
   131       by (auto elim!: effect_bindE effect_ifE effect_nthE effect_returnE effect_updE) fastforce
   132   qed
   133 qed
   134 
   135 lemma part_outer_remains:
   136   assumes "effect (part1 a l r p) h h' rs"
   137   shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i"
   138   using assms
   139 proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
   140   case (1 a l r p h h' rs)
   141   note cr = `effect (part1 a l r p) h h' rs`
   142   
   143   show ?case
   144   proof (cases "r \<le> l")
   145     case True (* Terminating case *)
   146     with cr show ?thesis
   147       unfolding part1.simps[of a l r p]
   148       by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
   149   next
   150     case False (* recursive case *)
   151     note rec_condition = this
   152     let ?v = "Array.get h a ! l"
   153     show ?thesis
   154     proof (cases "?v \<le> p")
   155       case True
   156       with cr False
   157       have rec1: "effect (part1 a (l + 1) r p) h h' rs"
   158         unfolding part1.simps[of a l r p]
   159         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
   160       from 1(1)[OF rec_condition True rec1]
   161       show ?thesis by fastforce
   162     next
   163       case False
   164       with rec_condition cr
   165       obtain h1 where swp: "effect (swap a l r) h h1 ()"
   166         and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
   167         unfolding part1.simps[of a l r p]
   168         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
   169       from swp rec_condition have
   170         "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h a ! i = Array.get h1 a ! i"
   171         unfolding swap_def
   172         by (elim effect_bindE effect_nthE effect_updE effect_returnE) auto
   173       with 1(2) [OF rec_condition False rec2] show ?thesis by fastforce
   174     qed
   175   qed
   176 qed
   177 
   178 
   179 lemma part_partitions:
   180   assumes "effect (part1 a l r p) h h' rs"
   181   shows "(\<forall>i. l \<le> i \<and> i < rs \<longrightarrow> Array.get h' (a::nat array) ! i \<le> p)
   182   \<and> (\<forall>i. rs < i \<and> i \<le> r \<longrightarrow> Array.get h' a ! i \<ge> p)"
   183   using assms
   184 proof (induct a l r p arbitrary: h h' rs rule:part1.induct)
   185   case (1 a l r p h h' rs)
   186   note cr = `effect (part1 a l r p) h h' rs`
   187   
   188   show ?case
   189   proof (cases "r \<le> l")
   190     case True (* Terminating case *)
   191     with cr have "rs = r"
   192       unfolding part1.simps[of a l r p]
   193       by (elim effect_bindE effect_ifE effect_returnE effect_nthE) auto
   194     with True
   195     show ?thesis by auto
   196   next
   197     case False (* recursive case *)
   198     note lr = this
   199     let ?v = "Array.get h a ! l"
   200     show ?thesis
   201     proof (cases "?v \<le> p")
   202       case True
   203       with lr cr
   204       have rec1: "effect (part1 a (l + 1) r p) h h' rs"
   205         unfolding part1.simps[of a l r p]
   206         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
   207       from True part_outer_remains[OF rec1] have a_l: "Array.get h' a ! l \<le> p"
   208         by fastforce
   209       have "\<forall>i. (l \<le> i = (l = i \<or> Suc l \<le> i))" by arith
   210       with 1(1)[OF False True rec1] a_l show ?thesis
   211         by auto
   212     next
   213       case False
   214       with lr cr
   215       obtain h1 where swp: "effect (swap a l r) h h1 ()"
   216         and rec2: "effect (part1 a l (r - 1) p) h1 h' rs"
   217         unfolding part1.simps[of a l r p]
   218         by (elim effect_bindE effect_nthE effect_ifE effect_returnE) auto
   219       from swp False have "Array.get h1 a ! r \<ge> p"
   220         unfolding swap_def
   221         by (auto simp add: Array.length_def elim!: effect_bindE effect_nthE effect_updE effect_returnE)
   222       with part_outer_remains [OF rec2] lr have a_r: "Array.get h' a ! r \<ge> p"
   223         by fastforce
   224       have "\<forall>i. (i \<le> r = (i = r \<or> i \<le> r - 1))" by arith
   225       with 1(2)[OF lr False rec2] a_r show ?thesis
   226         by auto
   227     qed
   228   qed
   229 qed
   230 
   231 
   232 fun partition :: "nat array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat Heap"
   233 where
   234   "partition a left right = do {
   235      pivot \<leftarrow> Array.nth a right;
   236      middle \<leftarrow> part1 a left (right - 1) pivot;
   237      v \<leftarrow> Array.nth a middle;
   238      m \<leftarrow> return (if (v \<le> pivot) then (middle + 1) else middle);
   239      swap a m right;
   240      return m
   241    }"
   242 
   243 declare partition.simps[simp del]
   244 
   245 lemma partition_permutes:
   246   assumes "effect (partition a l r) h h' rs"
   247   shows "multiset_of (Array.get h' a) 
   248   = multiset_of (Array.get h a)"
   249 proof -
   250     from assms part_permutes swap_permutes show ?thesis
   251       unfolding partition.simps
   252       by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) auto
   253 qed
   254 
   255 lemma partition_length_remains:
   256   assumes "effect (partition a l r) h h' rs"
   257   shows "Array.length h a = Array.length h' a"
   258 proof -
   259   from assms part_length_remains show ?thesis
   260     unfolding partition.simps swap_def
   261     by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) auto
   262 qed
   263 
   264 lemma partition_outer_remains:
   265   assumes "effect (partition a l r) h h' rs"
   266   assumes "l < r"
   267   shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i"
   268 proof -
   269   from assms part_outer_remains part_returns_index_in_bounds show ?thesis
   270     unfolding partition.simps swap_def
   271     by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) fastforce
   272 qed
   273 
   274 lemma partition_returns_index_in_bounds:
   275   assumes effect: "effect (partition a l r) h h' rs"
   276   assumes "l < r"
   277   shows "l \<le> rs \<and> rs \<le> r"
   278 proof -
   279   from effect obtain middle h'' p where part: "effect (part1 a l (r - 1) p) h h'' middle"
   280     and rs_equals: "rs = (if Array.get h'' a ! middle \<le> Array.get h a ! r then middle + 1
   281          else middle)"
   282     unfolding partition.simps
   283     by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp 
   284   from `l < r` have "l \<le> r - 1" by arith
   285   from part_returns_index_in_bounds[OF part this] rs_equals `l < r` show ?thesis by auto
   286 qed
   287 
   288 lemma partition_partitions:
   289   assumes effect: "effect (partition a l r) h h' rs"
   290   assumes "l < r"
   291   shows "(\<forall>i. l \<le> i \<and> i < rs \<longrightarrow> Array.get h' (a::nat array) ! i \<le> Array.get h' a ! rs) \<and>
   292   (\<forall>i. rs < i \<and> i \<le> r \<longrightarrow> Array.get h' a ! rs \<le> Array.get h' a ! i)"
   293 proof -
   294   let ?pivot = "Array.get h a ! r" 
   295   from effect obtain middle h1 where part: "effect (part1 a l (r - 1) ?pivot) h h1 middle"
   296     and swap: "effect (swap a rs r) h1 h' ()"
   297     and rs_equals: "rs = (if Array.get h1 a ! middle \<le> ?pivot then middle + 1
   298          else middle)"
   299     unfolding partition.simps
   300     by (elim effect_bindE effect_returnE effect_nthE effect_ifE effect_updE) simp
   301   from swap have h'_def: "h' = Array.update a r (Array.get h1 a ! rs)
   302     (Array.update a rs (Array.get h1 a ! r) h1)"
   303     unfolding swap_def
   304     by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp
   305   from swap have in_bounds: "r < Array.length h1 a \<and> rs < Array.length h1 a"
   306     unfolding swap_def
   307     by (elim effect_bindE effect_returnE effect_nthE effect_updE) simp
   308   from swap have swap_length_remains: "Array.length h1 a = Array.length h' a"
   309     unfolding swap_def by (elim effect_bindE effect_returnE effect_nthE effect_updE) auto
   310   from `l < r` have "l \<le> r - 1" by simp
   311   note middle_in_bounds = part_returns_index_in_bounds[OF part this]
   312   from part_outer_remains[OF part] `l < r`
   313   have "Array.get h a ! r = Array.get h1 a ! r"
   314     by fastforce
   315   with swap
   316   have right_remains: "Array.get h a ! r = Array.get h' a ! rs"
   317     unfolding swap_def
   318     by (auto simp add: Array.length_def elim!: effect_bindE effect_returnE effect_nthE effect_updE) (cases "r = rs", auto)
   319   from part_partitions [OF part]
   320   show ?thesis
   321   proof (cases "Array.get h1 a ! middle \<le> ?pivot")
   322     case True
   323     with rs_equals have rs_equals: "rs = middle + 1" by simp
   324     { 
   325       fix i
   326       assume i_is_left: "l \<le> i \<and> i < rs"
   327       with swap_length_remains in_bounds middle_in_bounds rs_equals `l < r`
   328       have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
   329       from i_is_left rs_equals have "l \<le> i \<and> i < middle \<or> i = middle" by arith
   330       with part_partitions[OF part] right_remains True
   331       have "Array.get h1 a ! i \<le> Array.get h' a ! rs" by fastforce
   332       with i_props h'_def in_bounds have "Array.get h' a ! i \<le> Array.get h' a ! rs"
   333         unfolding Array.update_def Array.length_def by simp
   334     }
   335     moreover
   336     {
   337       fix i
   338       assume "rs < i \<and> i \<le> r"
   339 
   340       hence "(rs < i \<and> i \<le> r - 1) \<or> (rs < i \<and> i = r)" by arith
   341       hence "Array.get h' a ! rs \<le> Array.get h' a ! i"
   342       proof
   343         assume i_is: "rs < i \<and> i \<le> r - 1"
   344         with swap_length_remains in_bounds middle_in_bounds rs_equals
   345         have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
   346         from part_partitions[OF part] rs_equals right_remains i_is
   347         have "Array.get h' a ! rs \<le> Array.get h1 a ! i"
   348           by fastforce
   349         with i_props h'_def show ?thesis by fastforce
   350       next
   351         assume i_is: "rs < i \<and> i = r"
   352         with rs_equals have "Suc middle \<noteq> r" by arith
   353         with middle_in_bounds `l < r` have "Suc middle \<le> r - 1" by arith
   354         with part_partitions[OF part] right_remains 
   355         have "Array.get h' a ! rs \<le> Array.get h1 a ! (Suc middle)"
   356           by fastforce
   357         with i_is True rs_equals right_remains h'_def
   358         show ?thesis using in_bounds
   359           unfolding Array.update_def Array.length_def
   360           by auto
   361       qed
   362     }
   363     ultimately show ?thesis by auto
   364   next
   365     case False
   366     with rs_equals have rs_equals: "middle = rs" by simp
   367     { 
   368       fix i
   369       assume i_is_left: "l \<le> i \<and> i < rs"
   370       with swap_length_remains in_bounds middle_in_bounds rs_equals
   371       have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
   372       from part_partitions[OF part] rs_equals right_remains i_is_left
   373       have "Array.get h1 a ! i \<le> Array.get h' a ! rs" by fastforce
   374       with i_props h'_def have "Array.get h' a ! i \<le> Array.get h' a ! rs"
   375         unfolding Array.update_def by simp
   376     }
   377     moreover
   378     {
   379       fix i
   380       assume "rs < i \<and> i \<le> r"
   381       hence "(rs < i \<and> i \<le> r - 1) \<or> i = r" by arith
   382       hence "Array.get h' a ! rs \<le> Array.get h' a ! i"
   383       proof
   384         assume i_is: "rs < i \<and> i \<le> r - 1"
   385         with swap_length_remains in_bounds middle_in_bounds rs_equals
   386         have i_props: "i < Array.length h' a" "i \<noteq> r" "i \<noteq> rs" by auto
   387         from part_partitions[OF part] rs_equals right_remains i_is
   388         have "Array.get h' a ! rs \<le> Array.get h1 a ! i"
   389           by fastforce
   390         with i_props h'_def show ?thesis by fastforce
   391       next
   392         assume i_is: "i = r"
   393         from i_is False rs_equals right_remains h'_def
   394         show ?thesis using in_bounds
   395           unfolding Array.update_def Array.length_def
   396           by auto
   397       qed
   398     }
   399     ultimately
   400     show ?thesis by auto
   401   qed
   402 qed
   403 
   404 
   405 function quicksort :: "nat array \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> unit Heap"
   406 where
   407   "quicksort arr left right =
   408      (if (right > left)  then
   409         do {
   410           pivotNewIndex \<leftarrow> partition arr left right;
   411           pivotNewIndex \<leftarrow> assert (\<lambda>x. left \<le> x \<and> x \<le> right) pivotNewIndex;
   412           quicksort arr left (pivotNewIndex - 1);
   413           quicksort arr (pivotNewIndex + 1) right
   414         }
   415      else return ())"
   416 by pat_completeness auto
   417 
   418 (* For termination, we must show that the pivotNewIndex is between left and right *) 
   419 termination
   420 by (relation "measure (\<lambda>(a, l, r). (r - l))") auto
   421 
   422 declare quicksort.simps[simp del]
   423 
   424 
   425 lemma quicksort_permutes:
   426   assumes "effect (quicksort a l r) h h' rs"
   427   shows "multiset_of (Array.get h' a) 
   428   = multiset_of (Array.get h a)"
   429   using assms
   430 proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
   431   case (1 a l r h h' rs)
   432   with partition_permutes show ?case
   433     unfolding quicksort.simps [of a l r]
   434     by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto
   435 qed
   436 
   437 lemma length_remains:
   438   assumes "effect (quicksort a l r) h h' rs"
   439   shows "Array.length h a = Array.length h' a"
   440 using assms
   441 proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
   442   case (1 a l r h h' rs)
   443   with partition_length_remains show ?case
   444     unfolding quicksort.simps [of a l r]
   445     by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto
   446 qed
   447 
   448 lemma quicksort_outer_remains:
   449   assumes "effect (quicksort a l r) h h' rs"
   450    shows "\<forall>i. i < l \<or> r < i \<longrightarrow> Array.get h (a::nat array) ! i = Array.get h' a ! i"
   451   using assms
   452 proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
   453   case (1 a l r h h' rs)
   454   note cr = `effect (quicksort a l r) h h' rs`
   455   thus ?case
   456   proof (cases "r > l")
   457     case False
   458     with cr have "h' = h"
   459       unfolding quicksort.simps [of a l r]
   460       by (elim effect_ifE effect_returnE) auto
   461     thus ?thesis by simp
   462   next
   463   case True
   464    { 
   465       fix h1 h2 p ret1 ret2 i
   466       assume part: "effect (partition a l r) h h1 p"
   467       assume qs1: "effect (quicksort a l (p - 1)) h1 h2 ret1"
   468       assume qs2: "effect (quicksort a (p + 1) r) h2 h' ret2"
   469       assume pivot: "l \<le> p \<and> p \<le> r"
   470       assume i_outer: "i < l \<or> r < i"
   471       from  partition_outer_remains [OF part True] i_outer
   472       have "Array.get h a !i = Array.get h1 a ! i" by fastforce
   473       moreover
   474       with 1(1) [OF True pivot qs1] pivot i_outer
   475       have "Array.get h1 a ! i = Array.get h2 a ! i" by auto
   476       moreover
   477       with qs2 1(2) [of p h2 h' ret2] True pivot i_outer
   478       have "Array.get h2 a ! i = Array.get h' a ! i" by auto
   479       ultimately have "Array.get h a ! i= Array.get h' a ! i" by simp
   480     }
   481     with cr show ?thesis
   482       unfolding quicksort.simps [of a l r]
   483       by (elim effect_ifE effect_bindE effect_assertE effect_returnE) auto
   484   qed
   485 qed
   486 
   487 lemma quicksort_is_skip:
   488   assumes "effect (quicksort a l r) h h' rs"
   489   shows "r \<le> l \<longrightarrow> h = h'"
   490   using assms
   491   unfolding quicksort.simps [of a l r]
   492   by (elim effect_ifE effect_returnE) auto
   493  
   494 lemma quicksort_sorts:
   495   assumes "effect (quicksort a l r) h h' rs"
   496   assumes l_r_length: "l < Array.length h a" "r < Array.length h a" 
   497   shows "sorted (subarray l (r + 1) a h')"
   498   using assms
   499 proof (induct a l r arbitrary: h h' rs rule: quicksort.induct)
   500   case (1 a l r h h' rs)
   501   note cr = `effect (quicksort a l r) h h' rs`
   502   thus ?case
   503   proof (cases "r > l")
   504     case False
   505     hence "l \<ge> r + 1 \<or> l = r" by arith 
   506     with length_remains[OF cr] 1(5) show ?thesis
   507       by (auto simp add: subarray_Nil subarray_single)
   508   next
   509     case True
   510     { 
   511       fix h1 h2 p
   512       assume part: "effect (partition a l r) h h1 p"
   513       assume qs1: "effect (quicksort a l (p - 1)) h1 h2 ()"
   514       assume qs2: "effect (quicksort a (p + 1) r) h2 h' ()"
   515       from partition_returns_index_in_bounds [OF part True]
   516       have pivot: "l\<le> p \<and> p \<le> r" .
   517      note length_remains = length_remains[OF qs2] length_remains[OF qs1] partition_length_remains[OF part]
   518       from quicksort_outer_remains [OF qs2] quicksort_outer_remains [OF qs1] pivot quicksort_is_skip[OF qs1]
   519       have pivot_unchanged: "Array.get h1 a ! p = Array.get h' a ! p" by (cases p, auto)
   520         (*-- First of all, by induction hypothesis both sublists are sorted. *)
   521       from 1(1)[OF True pivot qs1] length_remains pivot 1(5) 
   522       have IH1: "sorted (subarray l p a h2)"  by (cases p, auto simp add: subarray_Nil)
   523       from quicksort_outer_remains [OF qs2] length_remains
   524       have left_subarray_remains: "subarray l p a h2 = subarray l p a h'"
   525         by (simp add: subarray_eq_samelength_iff)
   526       with IH1 have IH1': "sorted (subarray l p a h')" by simp
   527       from 1(2)[OF True pivot qs2] pivot 1(5) length_remains
   528       have IH2: "sorted (subarray (p + 1) (r + 1) a h')"
   529         by (cases "Suc p \<le> r", auto simp add: subarray_Nil)
   530            (* -- Secondly, both sublists remain partitioned. *)
   531       from partition_partitions[OF part True]
   532       have part_conds1: "\<forall>j. j \<in> set (subarray l p a h1) \<longrightarrow> j \<le> Array.get h1 a ! p "
   533         and part_conds2: "\<forall>j. j \<in> set (subarray (p + 1) (r + 1) a h1) \<longrightarrow> Array.get h1 a ! p \<le> j"
   534         by (auto simp add: all_in_set_subarray_conv)
   535       from quicksort_outer_remains [OF qs1] quicksort_permutes [OF qs1] True
   536         length_remains 1(5) pivot multiset_of_sublist [of l p "Array.get h1 a" "Array.get h2 a"]
   537       have multiset_partconds1: "multiset_of (subarray l p a h2) = multiset_of (subarray l p a h1)"
   538         unfolding Array.length_def subarray_def by (cases p, auto)
   539       with left_subarray_remains part_conds1 pivot_unchanged
   540       have part_conds2': "\<forall>j. j \<in> set (subarray l p a h') \<longrightarrow> j \<le> Array.get h' a ! p"
   541         by (simp, subst set_of_multiset_of[symmetric], simp)
   542           (* -- These steps are the analogous for the right sublist \<dots> *)
   543       from quicksort_outer_remains [OF qs1] length_remains
   544       have right_subarray_remains: "subarray (p + 1) (r + 1) a h1 = subarray (p + 1) (r + 1) a h2"
   545         by (auto simp add: subarray_eq_samelength_iff)
   546       from quicksort_outer_remains [OF qs2] quicksort_permutes [OF qs2] True
   547         length_remains 1(5) pivot multiset_of_sublist [of "p + 1" "r + 1" "Array.get h2 a" "Array.get h' a"]
   548       have multiset_partconds2: "multiset_of (subarray (p + 1) (r + 1) a h') = multiset_of (subarray (p + 1) (r + 1) a h2)"
   549         unfolding Array.length_def subarray_def by auto
   550       with right_subarray_remains part_conds2 pivot_unchanged
   551       have part_conds1': "\<forall>j. j \<in> set (subarray (p + 1) (r + 1) a h') \<longrightarrow> Array.get h' a ! p \<le> j"
   552         by (simp, subst set_of_multiset_of[symmetric], simp)
   553           (* -- Thirdly and finally, we show that the array is sorted
   554           following from the facts above. *)
   555       from True pivot 1(5) length_remains have "subarray l (r + 1) a h' = subarray l p a h' @ [Array.get h' a ! p] @ subarray (p + 1) (r + 1) a h'"
   556         by (simp add: subarray_nth_array_Cons, cases "l < p") (auto simp add: subarray_append subarray_Nil)
   557       with IH1' IH2 part_conds1' part_conds2' pivot have ?thesis
   558         unfolding subarray_def
   559         apply (auto simp add: sorted_append sorted_Cons all_in_set_sublist'_conv)
   560         by (auto simp add: set_sublist' dest: le_trans [of _ "Array.get h' a ! p"])
   561     }
   562     with True cr show ?thesis
   563       unfolding quicksort.simps [of a l r]
   564       by (elim effect_ifE effect_returnE effect_bindE effect_assertE) auto
   565   qed
   566 qed
   567 
   568 
   569 lemma quicksort_is_sort:
   570   assumes effect: "effect (quicksort a 0 (Array.length h a - 1)) h h' rs"
   571   shows "Array.get h' a = sort (Array.get h a)"
   572 proof (cases "Array.get h a = []")
   573   case True
   574   with quicksort_is_skip[OF effect] show ?thesis
   575   unfolding Array.length_def by simp
   576 next
   577   case False
   578   from quicksort_sorts [OF effect] False have "sorted (sublist' 0 (List.length (Array.get h a)) (Array.get h' a))"
   579     unfolding Array.length_def subarray_def by auto
   580   with length_remains[OF effect] have "sorted (Array.get h' a)"
   581     unfolding Array.length_def by simp
   582   with quicksort_permutes [OF effect] properties_for_sort show ?thesis by fastforce
   583 qed
   584 
   585 subsection {* No Errors in quicksort *}
   586 text {* We have proved that quicksort sorts (if no exceptions occur).
   587 We will now show that exceptions do not occur. *}
   588 
   589 lemma success_part1I: 
   590   assumes "l < Array.length h a" "r < Array.length h a"
   591   shows "success (part1 a l r p) h"
   592   using assms
   593 proof (induct a l r p arbitrary: h rule: part1.induct)
   594   case (1 a l r p)
   595   thus ?case unfolding part1.simps [of a l r]
   596   apply (auto intro!: success_intros simp add: not_le)
   597   apply (auto intro!: effect_intros)
   598   done
   599 qed
   600 
   601 lemma success_bindI' [success_intros]: (*FIXME move*)
   602   assumes "success f h"
   603   assumes "\<And>h' r. effect f h h' r \<Longrightarrow> success (g r) h'"
   604   shows "success (f \<guillemotright>= g) h"
   605 using assms(1) proof (rule success_effectE)
   606   fix h' r
   607   assume "effect f h h' r"
   608   moreover with assms(2) have "success (g r) h'" .
   609   ultimately show "success (f \<guillemotright>= g) h" by (rule success_bind_effectI)
   610 qed
   611 
   612 lemma success_partitionI:
   613   assumes "l < r" "l < Array.length h a" "r < Array.length h a"
   614   shows "success (partition a l r) h"
   615 using assms unfolding partition.simps swap_def
   616 apply (auto intro!: success_bindI' success_ifI success_returnI success_nthI success_updI success_part1I elim!: effect_bindE effect_updE effect_nthE effect_returnE simp add:)
   617 apply (frule part_length_remains)
   618 apply (frule part_returns_index_in_bounds)
   619 apply auto
   620 apply (frule part_length_remains)
   621 apply (frule part_returns_index_in_bounds)
   622 apply auto
   623 apply (frule part_length_remains)
   624 apply auto
   625 done
   626 
   627 lemma success_quicksortI:
   628   assumes "l < Array.length h a" "r < Array.length h a"
   629   shows "success (quicksort a l r) h"
   630 using assms
   631 proof (induct a l r arbitrary: h rule: quicksort.induct)
   632   case (1 a l ri h)
   633   thus ?case
   634     unfolding quicksort.simps [of a l ri]
   635     apply (auto intro!: success_ifI success_bindI' success_returnI success_nthI success_updI success_assertI success_partitionI)
   636     apply (frule partition_returns_index_in_bounds)
   637     apply auto
   638     apply (frule partition_returns_index_in_bounds)
   639     apply auto
   640     apply (auto elim!: effect_assertE dest!: partition_length_remains length_remains)
   641     apply (subgoal_tac "Suc r \<le> ri \<or> r = ri") 
   642     apply (erule disjE)
   643     apply auto
   644     unfolding quicksort.simps [of a "Suc ri" ri]
   645     apply (auto intro!: success_ifI success_returnI)
   646     done
   647 qed
   648 
   649 
   650 subsection {* Example *}
   651 
   652 definition "qsort a = do {
   653     k \<leftarrow> Array.len a;
   654     quicksort a 0 (k - 1);
   655     return a
   656   }"
   657 
   658 code_reserved SML upto
   659 
   660 ML {* @{code qsort} (Array.fromList [42, 2, 3, 5, 0, 1705, 8, 3, 15]) () *}
   661 
   662 export_code qsort checking SML SML_imp OCaml? OCaml_imp? Haskell? Scala? Scala_imp?
   663 
   664 end