[英]Inserting in to an Ordered Array using Binary Search
以下是我到目前為止所擁有的。 問題是如何找到插入點。 我在紙上做了一些手工描and,最終觀察到的是下限和上限相等,並且插入點始終比下限和上限相等時的索引高。
我知道在線上有很多解決方案,但是我真的想自己理解這一點,因為我只在自己學習時才學習並記住事情,而不是試圖弄清楚其他人是如何提出解決方案的。
如果有人可以指導我,那就太好了。 同樣,一旦我獲得了插入點,我就可以做其余的工作,即將所有值都降低一個索引以形成插入值點。
public void insert(long value) {
int lowerBound = 0;
int upperBound = nElems - 1;
int curIn;
while (true) {
curIn = (lowerBound + upperBound) / 2;
if (a[curIn] < value)
lowerBound = curIn + 1;
else
upperBound = curIn - 1;
}
二進制搜索必須檢查循環內的三種情況:
當lowerBound
等於upperBound
並且所討論的位置不等於所搜索的值時,二進制搜索應中止。
無論如何,搜索結束的位置就是您要插入值的位置:如果該位置的值等於您要插入的值,則在此位置或之后插入都沒關系。 如果較小,則要在此位置之后插入;如果較大,則要在此位置插入。
我不會給出代碼,因為OP顯然只是要求提示。
希望這會有所幫助:
public void insert(long value) {
int lowerBound = 0;
int upperBound = nElems - 1;
int curIn;
while (lowerBound!=upperBound) { //terminating condition - otherwise you will obtain an infinite loop.
curIn = (lowerBound + upperBound) / 2;
//take a choice: put your element immediately before a greater element.
if (a[curIn] <= value) { //also the same value must be managed as more little than the current.
lowerBound = curIn + 1;
} else {
//You cannot skip curIn lowering down the upper limit, curIn should be the position you are looking for.
upperBound = curIn; // - 1;
}
}
insert_in_list( value, curIn ); //do it as you wish. place the new element in the curIn position
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.