Problem: quick_sort

Your task is to implement a deterministic variant of Quick Sort and verify its correctness in Dafny. The pivot must always be chosen as the first element of the slice (or sub-slice) being sorted. You need to implement: (1) partition: Reorders the slice such that all elements less than the pivot come before it, and all elements greater than or equal to the pivot come after it. It returns the final index of the pivot. (2) quick_sort: Recursive calls using the partition index, which is the function to be verified. There are several verification challenges: (1) Partitioning: Proving that the partition function permutes the array such that [< pivot, pivot, >= pivot] holds. (2) Termination: Proving that the recursive calls are strictly smaller. With pivot = first, if you aren't careful, a sorted array might result in a recursive call of size n-1 and 0. You must prove the pivot index is strictly bounded to ensure the recursion measure decreases. Note that you are not allowed to write new axioms (for example, writing seemingly correct property for multisets), and maybe directly using permutation is a better option.

// Following is the block for necessary definitions
// <preamble>
ghost predicate is_sorted(s: seq<int>) {
    forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]
}

ghost predicate is_valid_index_permutation(p: seq<int>, n: int) {
    && |p| == n
    && (forall i {:trigger p[i]} :: 0 <= i < n ==> 0 <= p[i] < n)
    && (forall i, j {:trigger p[i], p[j]} :: 0 <= i < j < n ==> p[i] != p[j])
}

ghost predicate is_permutation(v1: seq<int>, v2: seq<int>) {
    exists p: seq<int> :: 
        is_valid_index_permutation(p, |v1|) 
        && |v1| == |v2|
        && (forall i {:trigger p[i]} :: 0 <= i < |v1| ==> v2[i] == v1[p[i]])
}
// </preamble>

// Following is the block for potential helper specifications
// <helpers>

// </helpers>

// Following is the block for proofs of lemmas
// <proofs>

// </proofs>

// Following is the block for the main specification
// <spec>
method quick_sort(v: seq<int>) returns (v_new: seq<int>)
    ensures is_sorted(v_new)
    ensures is_permutation(v, v_new)
// </spec>
// <code>
{
    // Implement and verify the Quick Sort algorithm here.
}
// </code>

method main() {}