首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dafny选择排序降序

Dafny选择排序降序
EN

Stack Overflow用户
提问于 2018-05-24 10:07:10
回答 1查看 318关注 0票数 0

下面是以降序执行选择排序的方法。但是,在while循环中的第一个不变量据说不是由循环维护的,为什么会这样呢?

代码语言:javascript
复制
 method sortDesc (a : array<int>) 
        modifies a;
        requires a != null;
        ensures forall m,n :: 0 <= m < n < a.Length ==> a[m] >= a[n];
        requires a.Length > 1;
        ensures multiset(a[..]) == multiset(old(a[..]));
    {
        var index := a.Length - 1;
        while(index > -1)
            invariant forall m,n :: 0 <= m <= index && index < n < a.Length ==> a[m] >= a[n];               // all elements that we have not sorted are bigger than any element we have sorted  !!!!!!!!!!!!
            invariant a.Length > index > -1;
            invariant forall k,l :: index < k < l < a.Length ==> a[k] >= a[l];                              //the part we have gone through is already sorted!!
            invariant multiset(a[..]) == multiset(old(a[..]));                                      // USED TO MAKE SURE ALL THE STARTING ELEMENTS ARE STILL THERE!!!!!
            decreases index;
        {
            var minIndex := findMinBetween(a, index, a.Length);
            if (a[index] < a[minIndex]) 
            {
                a[index], a[minIndex] := a[minIndex],a[index];                               //SWAP ELEMENTS!!!
            }
            if (index == 0)
            {
                return;
            }
            index := index - 1;
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-24 13:57:05

也许a[index] < a[minIndex]的比较是错误的。您正在尝试将小东西移到右边,所以如果a[minindex]a[index]小,您需要将它(a[minindex])移到右边。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50506544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档