| [d604c6f] | 1 | /* Challenge 3: part 1: the simple sequential algorithm
|
|---|
| 2 | * is verified.
|
|---|
| 3 | */
|
|---|
| 4 | #include <stdbool.h>
|
|---|
| 5 | typedef double T;
|
|---|
| 6 | $input int n, N = 5;
|
|---|
| 7 | $assume(1<=n && n<=N);
|
|---|
| 8 | $input T A[n]; // input: constant, fixed forever
|
|---|
| 9 |
|
|---|
| 10 | /* Counts the number of occurences of val in the array
|
|---|
| 11 | * starting at p consisting of n ints */
|
|---|
| 12 | int count(int n, T *p, T val) {
|
|---|
| 13 | int result = 0;
|
|---|
| 14 | for (int i=0; i < n; i++) if ((p[i]) == val) result++;
|
|---|
| 15 | return result;
|
|---|
| 16 | }
|
|---|
| 17 |
|
|---|
| 18 | /* Asserts the sequence starting at p2 is the permutation of that
|
|---|
| 19 | * starting at p1 with elements occurring in nondecreasing order */
|
|---|
| 20 | void assertSortOf(int n, T *p1, T *p2) {
|
|---|
| 21 | $assert($forall (int i : 0..n-2) p2[i]<=p2[i+1]);
|
|---|
| 22 | $assert($forall (int i : 0..n-1)
|
|---|
| 23 | $exists (int j : 0..n-1) p1[i]==p2[j]);
|
|---|
| 24 | for (int i=0; i<n; i++)
|
|---|
| 25 | $assert(count(n, p1, p2[i]) == count(n, p2, p2[i]));
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | void swap(T *p, int i, int j) {
|
|---|
| 29 | T temp = p[i];
|
|---|
| 30 | p[i] = p[j];
|
|---|
| 31 | p[j] = temp;
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | void oddEvenSort(int n, T *list) {
|
|---|
| 35 | _Bool sorted = false;
|
|---|
| 36 |
|
|---|
| 37 | while (!sorted) {
|
|---|
| 38 | sorted = true;
|
|---|
| 39 | for (int i = 1; i < n-1; i += 2) {
|
|---|
| 40 | if (list[i] > list[i+1]) {
|
|---|
| 41 | swap(list, i, i+1);
|
|---|
| 42 | sorted = false;
|
|---|
| 43 | }
|
|---|
| 44 | }
|
|---|
| 45 | for (int i = 0; i < n-1; i += 2) {
|
|---|
| 46 | if (list[i] > list[i+1]) {
|
|---|
| 47 | swap(list, i, i+1);
|
|---|
| 48 | sorted = false;
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 | }
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | int main() {
|
|---|
| 55 | T a[n];
|
|---|
| 56 | for (int i=0; i<n; i++) a[i] = A[i];
|
|---|
| 57 | oddEvenSort(n, a);
|
|---|
| 58 | assertSortOf(n, A, a);
|
|---|
| 59 | }
|
|---|