Reputation: 1658
The following is what i have so far. The problem is how do i find the insertion spot. I did some hand tracing on paper and what i observed was eventually the lowerbound and upperbound equal and the insertion spot is always a index higher than the index of lower and upper bounds when they are equal.
I know there are many solutions online but i am really trying to understand this on my own since i only learn and remember things when i learn on my own rather than trying to figure out how others came up with a solution.
If someone can guide me it would be great. Also once i get the insertion spot i can do the rest which is moving all the values a index lower to make spot for the insertion value.
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;
}
Upvotes: 0
Views: 935
Reputation: 1120
Binary search has to check for three cases inside the loop:
Binary search should abort, when the lowerBound
equals the upperBound
and the position in question is not equal to the value searched for.
Anyway, the position at which the search ends is the position where you want to insert the value: if the value at that position equals the value you want to insert, it doesn't matter if you insert at this position or after. If it is smaller, you want to insert after this position, if it is larger, you want to insert at this position.
I won't give code, as OP clearly just asked for a hint.
Upvotes: 2
Reputation: 1062
Hope this may help:
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
}
Upvotes: 0