讓我們在一張紙上運行你的代碼,看看這兩種方法會發生什麼;我將使用這個表示法:3.idx
作爲從輸入中指向元素3的迭代器。
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg)/2;
while(mid != end && *mid != key)
{
if (key < *mid)
end = mid; //why not end = mid - 1??
else
beg = mid + 1;
mid = beg + (end - beg)/2;
}
讓我們來運行它:
Input: `12345`.
Key: `-10`.
beg = 1
end = 5
mid = 3
3.idx != 5.idx and 3 not -10
if(-10 < 3)
end.idx = 3.idx
mid.idx = 1.idx + 1 = 2
Now we check only "123":
2.idx != 3.idx and 2 not -10
if(-10 < 2)
end.idx = 2.idx
mid.idx = 1.idx + 0 = 1
Now we check only "12":
1.idx != 2.idx and 1 not -10
if(-10 < 1)
end.idx = 1.idx
mid.idx = 1.idx + 0 = 1
Now we check only "1":
1.idx == 1.idx stop.
與
現在:
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg)/2;
while(mid != end && *mid != key)
{
if (key < *mid)
end = mid - 1 // Only change
else
beg = mid + 1;
mid = beg + (end - beg)/2;
}
,我們將得到:
Input: `12345`.
Key: `-10`.
beg = 1
end = 5
mid = 3
3.idx != 5.idx and 3 not -10
if(-10 < 3)
end.idx = 3.idx - 1 = 2.idx
mid.idx = 1.idx + 0 = 1
Now we check only "12":
1.idx != 2.idx and 1 not -10
STOP,你有沒有看到發生了什麼?
我們沒有檢查,如果2竟是key
,但我們應該這樣做...;)
它幫助我很多!謝謝 !! –