1
我如何從不變量中得知l是要返回的正確值以及如何初始化l =低;和h =高;建立不變式?循環不變式快速排序
/* invariant
* low <= l <= h <= high
* In region for indexes i with low <= i < end:
* elements are as originally, but rearranged.
* if i < l then arr[i] < x
* if i >= h then arr[i] >= x
* Elements outside region are unchanged.
*/
private static int partition(int[] arr, int low, int high, int x)
{
int l = low;
int h = high;
while (l<h)
{
if (arr[l] < x)
l =l +1;
else
{
int x = arr[l];
arr[l] = arr[h-1];
arr[h-1] = x
h = h-1;
}
}
return l;
}
我明白這個方法是做什麼的,我的問題僅僅是關於循環不變性,我如何從不變量中理解l是要返回的正確值以及l = low的初始化程度;和h =高;建立不變式? – user1795732
@ user1795732你的不變量的表達式是什麼? – dreamcrash
@ user1795732從'l = low;'和'h = high;'開始並保持交換符合條件的元素,並相應地將l更新爲l = 1 +1;'h'爲'h = h- 1;'。這使'l'上升,'h'下降。現在注意你的循環條件'while(l