0
你好我有一個問題,我不知道我的實現是否使用二進制搜索插入到向量中是正確的。 我有兩個向量一個存儲類對象。第二個是假設要排序的那個。第二個向量保存第一個向量的索引,這些索引假設按照字典順序排序(從小到大)。我試圖讓我的程序運行O(log(n))。這是我有...如何使用二進制搜索將元素插入到已排序的向量中
void Trendtracker:: add_hashtag(string ht)
{
Entry tweet;
tweet.count = 0;
tweet.hashtag = ht;
if (E.empty())
{
E.push_back(tweet);
S.push_back(0);
}
int l, m, r;
l = 0;
r = S.size() -1;
while (l < r)
{
m =(l+r)/2;
if(E[S[m]].hashtag == ht)//found #1
return;
else if (E[S[m]].hashtag < ht)// searches right
l = m +1;
else
r = m-1; // searches left
}
if(l ==r && E[S[l]].hashtag == tweet.hashtag)// found #2
return;
E.push_back(tweet);
//if not found and lower than the lowest
if(l==0 && ht < E[S[l]].hashtag)
{
//S[0]= E.size()-1;
S.insert(S.begin(), E.size()-1);
}
// if not found but is higher than highest
else if(l == S.size()-1 && E[S[l]].hashtag < ht)
{
S.push_back(E.size()-1);
}
// if new hashtag goes in the second index
else if(l==0&& r==0 && E[S[r]].hashtag< ht)
{
S.insert(S.begin()+1, E.size()-1);
}
// if not found and l & r are somewhere in the middle
else
{
S.insert(S.begin()+l, E.size()-1);
}
}
使用類似'的std :: LOWER_BOUND()',而不是滾動您自己:http://en.cppreference.com/w/cpp/algorithm/lower_bound –
如果'如果(E .empty())'條件爲真,那麼你可以在執行該'if'塊後返回。執行其餘代碼沒有意義。 – MKR