Why don't you use the built in function (bsearch)?
Main Topics
Browse All TopicsAssume I have a sorted array of integer numbers. Now I add a integer number into that array such that it still is in order after adding number .
I know I need to find a position to insert my number . The code as following
int mybseach(int *SortedArray, int numEle, int target )
{
int i;
for( i=0; i< numEle; i++)
if( target <= SortedArray[i] )
break;
return i;
}
However, it is not good because big O is O(n). Now I want to change it to "binary search" . Could someone give me that source code ?
Note :
1. This is not a homework . In fact, I lost my implement for that problem .
2. Because it is a "classical" problem, I don't need the pseudo code . I only need the good source code without bug .
Thank for reading .
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Hi Thienpnguyen,
Sorry about it not working.
What about this, does this work?
int
mybseach(int *SortedArray, int numEle, int target )
{
int current_Upper_Bound=numEle
int current_Lower_Bound=0;
int current_Range;
while(true)
{
current_Range=
current_Upper_Bound-
current_Lower_Bound;
if(current_Range==0)
{
break;
}
current_Divider=
current_Lower_Bound+
current_Range/2;
if(target<=Sorted_Array[cu
{
current_Upper_Bound=curren
}
else
{
current_Lower_Bound=curren
}
}
return current_Lower_Bound;
}
Hi, all!
For glebspy: your code still has a little math problem:
current_Divider =
current_Lower_Bound + current_Range/2; // ?!?!?
That's hardly the middle of the interval. I'm sure you didn't check close enough, and I'm sure you meant:
current_Divider =
(current_Lower_Bound + current_Range) / 2;
And another thing:
Even if the search is O( lg2 n ), I'm sure you all know adding the number in the array, is a completely different story. Now, if you were to use a binary three...
int binarysearch(int x[]/* input array */, int n /* no of elements */, int t /* key */)
{ int l, u, m;
l = -1;
u = n;
while (l+1 != u) {
m = (l + u) / 2;
if (x[m] < t)
l = m;
else
u = m;
}
/* if (u >= n || x[u] != t)
return -1;
*/
return u; /* return position */
}
The original code returns -1 if the key is not found. Since you need the position at which the key is to be inserted even if it is not found, simply get back the upper bound at which the search terminated. This is the position where you insert the key.
Example:
template<typename T>
size_t FindInsertionPoint(const T* Begin, const T* End, const T& Value)
{
const T* i = std::upper_bound(Begin, End, Value);
return i-Begin;
}
int main(int argc, char* argv[])
{
int A[12] = {1, 5, 6, 6, 7, 9, 9, 9, 12, 17, 17, 20};
int xi9 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi12 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi15 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi0 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi20 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi21 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
int xi22 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)],
return 0;
}
Hi, Thienpnguyen!
OK, I just have one question for you, and for you all, correct me if I'm wrong:
After you find the insertion point, given that you use an array, won't the actual insertion still be O(n)? ... because you will have to shift with one position all the remaining values.
So, instead (aside from the binary search algorithm), which is excellent just for a search, when you actually want to add a value, won't this be better:
(I presumed the array sorted ascending)
int InsertInSortedArray(int *SortedArray, int nE, int v)
{
int i;
for( i=nE; (i>0) && (SortedArray[i-1] > v) ; i--)
SortedArray[i] = SortedArray[i-1];
SortedArray[i] = v;
return i;
}
What do you think?
MFCRich,
Your function could be done with the built-in library functions with less code, and made more generic.
Example:
template<typename T>
size_t MFCRich_bsearch(const T* Begin, size_t size, const T& target)
{
const T* i = std::upper_bound(Begin, Begin+size, target);
if (i = Begin+size) return -1;
return i-Begin;
}
>>The question was about the binary search algorithm and I
>>think my code demonstrates it.
I understand, but what I'm trying to point out, is that the built-in STL functions can do binanry search.
I'm trying to point out to everyone here that there's no need to reinvent the wheel. Just use the built-in C++ functions.
Please look into the following piece of source, I may replicate the previous comments:
/*Binary search */
int bsearch( int key, int N, int* r )
{
unsigned int i,high,low;
if( N == 0 ) return 0;
for ( low=0, high=N-1; high >= low ; )
{
i = (high+low) / 2;
if ( key == r[i] )
return( i );
else if(key < r[i] )
high = i-1;
else
low = i+1;
}
return( -1 );
}
mbenassor,
I don't think you understand how a binary search works.
At worse time, a binary search can find an item in a list of 1024, by performing 12 hits.
Compare that to a Sequential-Search, which at worse time can find an item in a list of 1024, by performing 1024 hits.
The difference between a Sequential-Search and a binary search increases exponentially.
For example, a list of 16,777,216 at worse time with a binary search only requires 26 hits.
With a Sequential-Search, the worse time is 16,777,216.
A Sequential-Search can not compare in speed to a Binary Search.
Axter I understand how a binary search works
Did you read the q. of thienpnguyen ?
"Assume I have a sorted array of integer numbers. Now I add a integer number into that array such that
it still is in order after adding number ."
He wants to INSERT a number into a sorted array - you can search and find the correct position in log(n) time but how can you ADD the new number to that position without the need to shift all the following numbers ?!?!
This is not a linked list, the array is allocated in a continues memory block and the time of the insertion is LINEAR.
Think about it.
I guess we were talking apples and oranges.
I was referring to the search routine, and I didn't realize that you were referring to the insertion mechanism.
I agree, that the insertion is linear, but IMHO the questioner is asking about the search algorithm, and not the insertion mechanism.
I assume that thienpnguyen knows that the insertion will be LINEAR and is only worried about having an optimized search routine.
Other then changing the array to a link list, there's not much you can do about the linear insertion.
You can however speed up the search by using the built-in binary search functions.
You can also make use of the built-in functions for the insertion routine, wish will also work faster then previous insertion functions post here.
Business Accounts
Answer for Membership
by: glebspyPosted on 2002-02-06 at 16:10:58ID: 6784225
Dear Thienpnguyen,
-1;
rrent_Divi der]) t_Divider; t_Divider;
How about something like this?
int
mybseach(int *SortedArray, int numEle, int target )
{
int current_Upper_Bound=numEle
int current_Lower_Bound=0;
while(true)
{
current_Range=
current_Upper_Bound-
current_Lower_Bound;
if(current_Range==0)
{
break;
}
current_Divider=
current_Lower_Bound+
current_Range/2;
if(target<=Sorted_Array[cu
{
current_Upper_Bound=curren
}
else
{
current_Lower_Bound=curren
}
}
return current_Lower_Bound;
}