我有以下方法以降序执行选择排序。但是,while循环中的非常第一个不变据说不是由循环维护的,为什么会这样呢?
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;
}
}
答案 0 :(得分:1)
也许比较a[index] < a[minIndex]
是错误的方法。您正试图将小东西移到右侧,因此如果a[minindex]
小于a[index]
,则需要将其移至右侧(a[minindex]
)。