-
Notifications
You must be signed in to change notification settings - Fork 88
/
mergesort.v
74 lines (70 loc) · 1.56 KB
/
mergesort.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Require Export Coq.Lists.List.
Require Export Coq.Arith.Arith.
Require Import Program.Wf.
Program Fixpoint merge (x : list nat) (y : list nat) {measure (length x + length y)} : list nat :=
match x with
| x1 :: xs =>
match y with
| y1 :: ys => if x1 <? y1
then x1::(merge xs y)
else y1::(merge x ys)
| _ => x
end
| _ => y
end.
Next Obligation.
apply Nat.add_le_lt_mono.
reflexivity.
auto.
Qed.
Lemma skipn_length (n : nat) :
forall {A} (l : list A), length (skipn n l) = length l - n.
Proof.
intros A.
induction n.
- intros l; simpl; rewrite Nat.sub_0_r; reflexivity.
- destruct l; simpl; auto.
Qed.
Program Fixpoint mergesort (x : list nat) {measure (length x)}: list nat :=
match x with
| nil => nil
| x :: nil => x :: nil
| x :: y :: nil => if x <? y
then (x :: y :: nil)
else (y :: x :: nil)
| x :: y :: z :: rest =>
let a := (x :: y :: z :: rest) in
let p := (Nat.div2 (length a)) in
merge (mergesort (firstn p a)) (mergesort (skipn p a))
end.
Next Obligation.
rewrite firstn_length.
simpl.
apply lt_n_S.
apply Nat.min_lt_iff.
left.
destruct (length rest).
auto.
apply lt_n_S.
destruct n.
auto.
rewrite Nat.lt_div2.
auto.
apply Nat.lt_0_succ.
Qed.
Next Obligation.
rewrite skipn_length.
simpl.
destruct (length rest).
auto.
destruct Nat.div2.
auto.
rewrite Nat.lt_succ_r.
rewrite Nat.le_succ_r.
left.
rewrite Nat.le_succ_r.
left.
rewrite Nat.le_sub_le_add_r.
apply le_plus_l.
Qed.
Eval compute in mergesort (5::9::1::3::4::6::6::3::2::nil).