Copyright | (c) Levent Erkok |
---|---|
License | BSD3 |
Maintainer | erkokl@gmail.com |
Stability | experimental |
Safe Haskell | None |
Language | Haskell2010 |
An implementation of merge-sort and its correctness.
- merge :: Ord a => [a] -> [a] -> [a]
- mergeSort :: Ord a => [a] -> [a]
- nonDecreasing :: Ord a => [a] -> Bool
- isPermutationOf :: Eq a => [a] -> [a] -> Bool
- mergeSortCorrect :: [Int] -> Bool
Implementing merge-sort
A straightforward implementation of merge sort. We simply divide the input list in to two halves so long as it has at least two elements, sort each half on its own, and then merge.
Proving correctness of sorting
There are two main parts to proving that a sorting algorithm is correct:
- Prove that the output is non-decreasing
- Prove that the output is a permutation of the input
nonDecreasing :: Ord a => [a] -> Bool Source
Check whether a given sequence is non-decreasing.
isPermutationOf :: Eq a => [a] -> [a] -> Bool Source
Check whether two given sequences are permutations. We simply check that each sequence is a subset of the other, when considered as a set. The check is slightly complicated for the need to account for possibly duplicated elements.
The correctness theorem
mergeSortCorrect :: [Int] -> Bool Source
Asserting correctness of merge-sort for a list of the given size. Note that we can
only check correctness for fixed-size lists. Also, the proof will get more and more
complicated for the backend SMT solver as n
increases. Here we try it with 4.
We have:
[SBV] tests/T48.hs:100:1-16 Proving "mergeSortCorrect", using Z3. [Z3] Q.E.D.