-
Notifications
You must be signed in to change notification settings - Fork 109
feat(Algorithms): Prove insertion sort is stable #446
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Arleee1
wants to merge
50
commits into
leanprover:main
Choose a base branch
from
Arleee1:insertionstable
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
50 commits
Select commit
Hold shift + click to select a range
8be8d07
Big PR
Shreyas4991 e50c8b0
Fixed worst case statement
Shreyas4991 79d77de
Linarith
Shreyas4991 c1e3323
More review fixes
Shreyas4991 ddab6f0
More review fixes
Shreyas4991 08decfa
More review fixes
Shreyas4991 a2b4782
More review fixes
Shreyas4991 54bb351
More review fixes
Shreyas4991 7ee16a0
More review fixes
Shreyas4991 cc806f0
More review fixes
Shreyas4991 a732ed8
Fix test file imports
Shreyas4991 2cee489
More review fixes
Shreyas4991 3e7edf2
small golfs
chenson2018 4789639
Update CslibTests/QueryModel/ProgExamples.lean
Shreyas4991 afcfd57
Add docstrings for test files
Shreyas4991 30a7905
Merge branch 'query-final-squash' of github.com:Shreyas4991/cslib int…
Shreyas4991 4e3d80c
simps in a tutorial example
Shreyas4991 9f3df4d
Suggested name change. Additionally add co-author list:
Shreyas4991 6db1fde
Merge branch 'main' of github.com:leanprover/cslib into query-final-s…
Shreyas4991 a9485da
Fix lake shake issues
Shreyas4991 6fef51f
Done
Shreyas4991 f479c93
Switch to bool
Shreyas4991 5e2a2f6
Lower bound
Shreyas4991 6b78316
GPT generated lower bound
Shreyas4991 4fab097
Added module
Shreyas4991 8097c61
exe mk_all
Shreyas4991 87e7ded
Minimize imports
Shreyas4991 3f71048
Done
Shreyas4991 57856b7
GPT finished the proof for lists with nodup
Shreyas4991 53c2ef3
Got it for infinite types as well
Shreyas4991 b712d16
remove deicsion tree proofs
Shreyas4991 1eeb2d8
Merge branch 'main' of github.com:leanprover/cslib into query-final-s…
Shreyas4991 7370fc6
Merge branch 'main' of github.com:leanprover/cslib into query-final-s…
Shreyas4991 df70978
Merge branch 'main' of github.com:leanprover/cslib into query-final-s…
Shreyas4991 275d827
Merge upstream main
Shreyas4991 e9cb648
Remove accidental file
Shreyas4991 7f4010e
Initialize clean up of lower bound proof
Shreyas4991 d04ca73
Include the model parametric style lower bound in the lower bound file
Shreyas4991 e7c8bde
Clean up
Shreyas4991 a8e9f3d
Clean up a bit
Shreyas4991 4ca216d
Merge branch 'main' into query-final-squash
Shreyas4991 30cf281
Remove Prop from structure
Shreyas4991 a145ded
docstring
Shreyas4991 6761169
Merge branch 'query-final-squash' of github.com:Shreyas4991/cslib int…
Shreyas4991 c6e1add
Where did prop typed structures sneak in. Purge them
Shreyas4991 e07de01
Where did prop typed structures sneak in. Purge them
Shreyas4991 cf9f1f5
Fix lint
Shreyas4991 56c98a5
Fix documentation for listLinearSearch evaluation
Shreyas4991 f46ca23
Prove insertionsort stability
Arleee1 efd984a
separate definition of stability into ListComparisonSort.lean
Arleee1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
158 changes: 158 additions & 0 deletions
158
Cslib/AlgorithmsTheory/Algorithms/ListInsertionSort.lean
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| /- | ||
| Copyright (c) 2026 Shreyas Srinivas. All rights reserved. | ||
| Released under Apache 2.0 license as described in the file LICENSE. | ||
| Authors: Shreyas Srinivas, Eric Wieser | ||
| -/ | ||
| module | ||
|
|
||
| public import Cslib.AlgorithmsTheory.Algorithms.ListOrderedInsert | ||
| public import Mathlib.Tactic.NormNum | ||
|
|
||
| @[expose] public section | ||
|
|
||
| /-! | ||
| # Insertion sort in a list | ||
|
|
||
| In this file we state and prove the correctness and complexity of insertion sort in lists under | ||
| the `SortOpsInsertHead` model. This insertionSort evaluates identically to the upstream version of | ||
| `List.insertionSort` | ||
| -- | ||
|
|
||
| ## Main Definitions | ||
|
|
||
| - `insertionSort` : Insertion sort algorithm in the `SortOpsInsertHead` query model | ||
|
|
||
| ## Main results | ||
|
|
||
| - `insertionSort_eval`: `insertionSort` evaluates identically to `List.insertionSort`. | ||
| - `insertionSort_permutation` : `insertionSort` outputs a permutation of the input list. | ||
| - `insertionSort_sorted` : `insertionSort` outputs a sorted list. | ||
| - `insertionSort_complexity` : `insertionSort` takes at most n * (n + 1) comparisons and | ||
| (n + 1) * (n + 2) list head-insertions. | ||
| - `insertionSort_stable` : `insertionSort` is a stable sorting algorithm. | ||
| -/ | ||
|
|
||
| namespace Cslib | ||
|
|
||
| namespace Algorithms | ||
|
|
||
| open Prog | ||
|
|
||
| /-- The insertionSort algorithms on lists with the `SortOps` query. -/ | ||
| def insertionSort (l : List α) : Prog (SortOpsInsertHead α) (List α) := | ||
| match l with | ||
| | [] => return [] | ||
| | x :: xs => do | ||
| let rest ← insertionSort xs | ||
| insertOrd x rest | ||
|
|
||
| @[simp] | ||
| theorem insertionSort_eval (l : List α) (le : α → α → Bool) : | ||
| (insertionSort l).eval (sortModel le) = l.insertionSort (fun x y => le x y = true) := by | ||
| induction l with simp_all [insertionSort] | ||
|
|
||
| theorem insertionSort_permutation (l : List α) (le : α → α → Bool) : | ||
| ((insertionSort l).eval (sortModel le)).Perm l := by | ||
| simp [insertionSort_eval, List.perm_insertionSort] | ||
|
|
||
| theorem insertionSort_sorted | ||
| (l : List α) (le : α → α → Bool) | ||
| [Std.Total (fun x y => le x y = true)] [IsTrans α (fun x y => le x y = true)] : | ||
| ((insertionSort l).eval (sortModel le)).Pairwise (fun x y => le x y = true) := by | ||
| simpa using List.pairwise_insertionSort _ _ | ||
|
|
||
| lemma insertionSort_length (l : List α) (le : α → α → Bool) : | ||
| ((insertionSort l).eval (sortModel le)).length = l.length := by | ||
| simp | ||
|
|
||
| lemma insertionSort_time_compares (head : α) (tail : List α) (le : α → α → Bool) : | ||
| ((insertionSort (head :: tail)).time (sortModel le)).compares = | ||
| ((insertionSort tail).time (sortModel le)).compares + | ||
| ((insertOrd head (tail.insertionSort (fun x y => le x y = true))).time | ||
| (sortModel le)).compares := by | ||
| simp [insertionSort] | ||
|
|
||
| lemma insertionSort_time_inserts (head : α) (tail : List α) (le : α → α → Bool) : | ||
| ((insertionSort (head :: tail)).time (sortModel le)).inserts = | ||
| ((insertionSort tail).time (sortModel le)).inserts + | ||
| ((insertOrd head (tail.insertionSort (fun x y => le x y = true))).time | ||
| (sortModel le)).inserts := by | ||
| simp [insertionSort] | ||
|
|
||
| theorem insertionSort_complexity (l : List α) (le : α → α → Bool) : | ||
| ((insertionSort l).time (sortModel le)) | ||
| ≤ ⟨l.length * (l.length + 1), (l.length + 1) * (l.length + 2)⟩ := by | ||
| induction l with | ||
| | nil => | ||
| simp [insertionSort] | ||
| | cons head tail ih => | ||
| grind [insertOrd_complexity_upper_bound, List.length_insertionSort, SortOpsCost.le_def, | ||
| insertionSort_time_compares, insertionSort_time_inserts] | ||
|
|
||
| section Stability | ||
|
|
||
| private lemma filter_orderedInsert_of_neg {r : α → α → Prop} [DecidableRel r] | ||
| (a : α) (l : List α) (p : α → Bool) (ha : p a = false) : | ||
| (l.orderedInsert r a).filter p = l.filter p := by | ||
| induction l with | ||
| | nil => rw [List.orderedInsert_nil]; simp [ha] | ||
| | cons b l ih => | ||
| rw [List.orderedInsert_cons] | ||
| split | ||
| · simp [List.filter, ha] | ||
| · simp only [List.filter]; split <;> simp [ih] | ||
|
|
||
| private lemma filter_orderedInsert_of_pos {r : α → α → Prop} [DecidableRel r] | ||
| (a : α) (l : List α) (p : α → Bool) | ||
| (ha : p a = true) | ||
| (hcompat : ∀ b, p b = true → r a b) | ||
| (hsorted : l.Pairwise r) : | ||
| (l.orderedInsert r a).filter p = a :: l.filter p := by | ||
| induction l with | ||
| | nil => rw [List.orderedInsert_nil]; simp [ha] | ||
| | cons b l ih => | ||
| rw [List.orderedInsert_cons] | ||
| rw [List.pairwise_cons] at hsorted | ||
| split | ||
| · simp [List.filter, ha] | ||
| · rename_i hnr | ||
| have hnpb : p b = false := by | ||
| by_contra h; push_neg at h | ||
| cases hpb : p b with | ||
| | false => simp [hpb] at h | ||
| | true => exact hnr (hcompat b hpb) | ||
| simp only [List.filter, hnpb] | ||
| exact ih hsorted.2 | ||
|
|
||
| theorem insertionSort_stable | ||
| (xs : List α) | ||
| (le : α → α → Bool) | ||
| [Std.Total (fun x y => le x y = true)] | ||
| [IsTrans α (fun x y => le x y = true)] : | ||
| IsStableSort (fun xs => (insertionSort xs).eval (sortModel le)) xs le := by | ||
| simp only [insertionSort_eval] | ||
| intro k | ||
| induction xs with | ||
| | nil => simp | ||
| | cons a rest ih => | ||
| change List.filter (fun x => le x k && le k x) | ||
| (List.insertionSort (fun x y => le x y = true) (a :: rest)) = | ||
| List.filter (fun x => le x k && le k x) (a :: rest) | ||
| rw [List.insertionSort_cons] | ||
| have hsorted : (rest.insertionSort (fun x y => le x y = true)).Pairwise | ||
| (fun x y => le x y = true) := | ||
| List.pairwise_insertionSort _ rest | ||
| rcases hab : (le a k && le k a) with _ | _ | ||
| · rw [filter_orderedInsert_of_neg a _ (fun x => le x k && le k x) hab] | ||
| simp [hab, ih] | ||
| · rw [filter_orderedInsert_of_pos a _ (fun x => le x k && le k x) hab _ hsorted] | ||
| · simp [hab, ih] | ||
| · intro b hb | ||
| simp only [Bool.and_eq_true] at hab hb | ||
| exact IsTrans.trans (r := fun x y => le x y = true) a k b hab.1 hb.2 | ||
|
|
||
| end Stability | ||
|
|
||
| end Algorithms | ||
|
|
||
| end Cslib | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| /- | ||
| Copyright (c) 2026 Shreyas Srinivas. All rights reserved. | ||
| Released under Apache 2.0 license as described in the file LICENSE. | ||
| Authors: Shreyas Srinivas, Eric Wieser | ||
| -/ | ||
|
|
||
| module | ||
|
|
||
| public import Cslib.AlgorithmsTheory.QueryModel | ||
| public import Cslib.AlgorithmsTheory.Models.ListComparisonSearch | ||
| public import Batteries.Data.List | ||
| public import Mathlib.Algebra.Order.Group.Nat | ||
| public import Mathlib.Tactic.Set | ||
|
|
||
| @[expose] public section | ||
|
|
||
| /-! | ||
| # Linear search in a list | ||
|
|
||
| In this file we state and prove the correctness and complexity of linear search in lists under | ||
| the `ListSearch` model. | ||
| -- | ||
|
|
||
| ## Main Definitions | ||
|
|
||
| - `listLinearSearch` : Linear search algorithm in the `ListSearch` query model | ||
|
|
||
| ## Main results | ||
|
|
||
| - `listLinearSearch_eval`: `listLinearSearch` evaluates identically to `List.contains`. | ||
| - `listLinearSearchM_time_complexity_upper_bound` : `linearSearch` takes at most `n` | ||
| comparison operations | ||
| - `listLinearSearchM_time_complexity_lower_bound` : There exist lists on which `linearSearch` needs | ||
| `n` comparisons | ||
| -/ | ||
| namespace Cslib | ||
|
|
||
| namespace Algorithms | ||
|
|
||
| open Prog | ||
|
|
||
| open ListSearch in | ||
| /-- Linear Search in Lists on top of the `ListSearch` query model. -/ | ||
| def listLinearSearch (l : List α) (x : α) : Prog (ListSearch α) Bool := do | ||
| match l with | ||
| | [] => return false | ||
| | l :: ls => | ||
| let cmp : Bool ← compare (l :: ls) x | ||
| if cmp then | ||
| return true | ||
| else | ||
| listLinearSearch ls x | ||
|
|
||
| @[simp, grind =] | ||
| lemma listLinearSearch_eval [BEq α] (l : List α) (x : α) : | ||
| (listLinearSearch l x).eval ListSearch.natCost = l.contains x := by | ||
| fun_induction l.elem x with simp_all [listLinearSearch] | ||
|
|
||
| lemma listLinearSearchM_correct_true [BEq α] [LawfulBEq α] (l : List α) | ||
| {x : α} (x_mem_l : x ∈ l) : (listLinearSearch l x).eval ListSearch.natCost = true := by | ||
| simp [x_mem_l] | ||
|
|
||
| lemma listLinearSearchM_correct_false [BEq α] [LawfulBEq α] (l : List α) | ||
| {x : α} (x_mem_l : x ∉ l) : (listLinearSearch l x).eval ListSearch.natCost = false := by | ||
| simp [x_mem_l] | ||
|
|
||
| lemma listLinearSearchM_time_complexity_upper_bound [BEq α] (l : List α) (x : α) : | ||
| (listLinearSearch l x).time ListSearch.natCost ≤ l.length := by | ||
| fun_induction l.elem x with | ||
| | case1 => simp [listLinearSearch] | ||
| | case2 => simp_all [listLinearSearch] | ||
| | case3 => | ||
| simp [listLinearSearch] | ||
| lia | ||
|
|
||
| lemma listLinearSearchM_time_complexity_lower_bound [DecidableEq α] [Nontrivial α] (n : ℕ) : | ||
| ∃ (l : List α) (x : α), l.length = n | ||
| ∧ (listLinearSearch l x).time ListSearch.natCost = l.length := by | ||
| obtain ⟨x, y, hneq⟩ := exists_pair_ne α | ||
| use List.replicate n y, x | ||
| split_ands | ||
| · simp | ||
| · induction n <;> simp [listLinearSearch, List.replicate] | ||
| grind [ListSearch.natCost_cost, ListSearch.natCost_evalQuery] | ||
|
|
||
| end Algorithms | ||
|
|
||
| end Cslib |
102 changes: 102 additions & 0 deletions
102
Cslib/AlgorithmsTheory/Algorithms/ListOrderedInsert.lean
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| /- | ||
| Copyright (c) 2026 Shreyas Srinivas. All rights reserved. | ||
| Released under Apache 2.0 license as described in the file LICENSE. | ||
| Authors: Shreyas Srinivas, Eric Wieser | ||
| -/ | ||
|
|
||
| module | ||
|
|
||
| public import Cslib.AlgorithmsTheory.QueryModel | ||
| public import Cslib.AlgorithmsTheory.Models.ListComparisonSort | ||
| public import Mathlib.Algebra.Order.Group.Nat | ||
| public import Mathlib.Data.Int.ConditionallyCompleteOrder | ||
| public import Mathlib.Data.List.Sort | ||
| public import Mathlib.Order.ConditionallyCompleteLattice.Basic | ||
|
|
||
| @[expose] public section | ||
|
|
||
| /-! | ||
| # Ordered insertion in a list | ||
|
|
||
| In this file we state and prove the correctness and complexity of ordered insertions in lists under | ||
| the `SortOps` model. This ordered insert is later used in `insertionSort` mirroring the structure | ||
| in upstream libraries for the pure lean code versions of these declarations. | ||
|
|
||
| -- | ||
|
|
||
| ## Main Definitions | ||
|
|
||
| - `insertOrd` : ordered insert algorithm in the `SortOps` query model | ||
|
|
||
| ## Main results | ||
|
|
||
| - `insertOrd_eval`: `insertOrd` evaluates identically to `List.orderedInsert`. | ||
| - `insertOrd_complexity_upper_bound` : Shows that `insertOrd` takes at most `n` comparisons, | ||
| and `n + 1` list head-insertion operations. | ||
| - `insertOrd_sorted` : Applying `insertOrd` to a sorted list yields a sorted list. | ||
| -/ | ||
|
|
||
| namespace Cslib | ||
| namespace Algorithms | ||
|
|
||
| open Prog | ||
|
|
||
| open SortOpsInsertHead | ||
|
|
||
| /-- | ||
| Performs ordered insertion of `x` into a list `l` in the `SortOps` query model. | ||
| If `l` is sorted, then `x` is inserted into `l` such that the resultant list is also sorted. | ||
| -/ | ||
| def insertOrd (x : α) (l : List α) : Prog (SortOpsInsertHead α) (List α) := do | ||
| match l with | ||
| | [] => insertHead x l | ||
| | a :: as => | ||
| if (← cmpLE x a : Bool) then | ||
| insertHead x (a :: as) | ||
| else | ||
| let res ← insertOrd x as | ||
| insertHead a res | ||
|
|
||
| @[simp] | ||
| lemma insertOrd_eval (x : α) (l : List α) (le : α → α → Bool) : | ||
| (insertOrd x l).eval (sortModel le) = l.orderedInsert (fun x y => le x y = true) x := by | ||
| induction l with | ||
| | nil => | ||
| simp [insertOrd, sortModel] | ||
| | cons head tail ih => | ||
| by_cases h_head : le x head | ||
| · simp [insertOrd, h_head] | ||
| · simp [insertOrd, h_head, ih] | ||
|
|
||
| -- TODO : to upstream | ||
| @[simp] | ||
| lemma _root_.List.length_orderedInsert (x : α) (l : List α) [DecidableRel r] : | ||
| (l.orderedInsert r x).length = l.length + 1 := by | ||
| induction l <;> grind | ||
|
|
||
| theorem insertOrd_complexity_upper_bound | ||
| (l : List α) (x : α) (le : α → α → Bool) : | ||
| (insertOrd x l).time (sortModel le) ≤ ⟨l.length, l.length + 1⟩ := by | ||
| induction l with | ||
| | nil => | ||
| simp [insertOrd, sortModel] | ||
| | cons head tail ih => | ||
| obtain ⟨ih_compares, ih_inserts⟩ := ih | ||
| rw [insertOrd] | ||
| by_cases h_head : le x head | ||
| · simp [h_head] | ||
| · simp [h_head] | ||
| grind | ||
|
|
||
| lemma insertOrd_sorted | ||
| (l : List α) (x : α) (le : α → α → Bool) | ||
| [Std.Total (fun x y => le x y)] | ||
| [IsTrans _ (fun x y => le x y)] : | ||
| l.Pairwise (fun x y => le x y) | ||
| → ((insertOrd x l).eval (sortModel le)).Pairwise (fun x y => le x y = true) := by | ||
| rw [insertOrd_eval] | ||
| exact List.Pairwise.orderedInsert _ _ | ||
|
|
||
| end Algorithms | ||
|
|
||
| end Cslib |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you should append your name here to the authors list. You are adding new content to this file.