Question

Binary Search

Asked by: 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 .

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.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2002-02-06 at 13:22:12ID20264001
Tags

search

,

binary

,

sort

Topics

C++ Programming Language

,

CYGWIN

Participating Experts
7
Points
100
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

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.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

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.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

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.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. binary
    What is the fastest way to insert a record with binary data in TQuery ? Andrew
  2. Binary Search
    How would i setup a binary search on an array with, oh, lets say 600 slots?
  3. Binary Sort
    I was just wondering if someone could give me the code for a binary sort function. In which you sort an array of numbers.
  4. binary search
    Hi, How to write a binary search in Delphi? It should only search an array of already sorted integers. Please one recursively and one using a loop. (with explanations) Regards Phi
  5. Integer to binary
    How to do integer to binary conversion?
  6. Binary Search & Recursion
    A program to create an array of records containing Name and ID_No (integer) fields which fills the data in the records randomly. Write down and thoroughly test a "binary search" function to return position of the record if found, otherwise zero. Wrute 2 versions o...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

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.

Join the Community

Answers

 

by: glebspyPosted on 2002-02-06 at 16:10:58ID: 6784225

Dear Thienpnguyen,

 How about something like this?

int
mybseach(int *SortedArray, int numEle, int target )
{
  int current_Upper_Bound=numEle-1;
  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[current_Divider])
        {
          current_Upper_Bound=current_Divider;
        }
      else
        {
          current_Lower_Bound=current_Divider;
        }
    }

  return current_Lower_Bound;
}

 

by: AxterPosted on 2002-02-06 at 16:18:35ID: 6784247

Why don't you use the built in function (bsearch)?

 

by: thienpnguyenPosted on 2002-02-06 at 16:24:11ID: 6784256

Axter>       Why don't you use the built in function (bsearch)?

bsearch returns a pointer to an occurrence of key in the array pointed to by base. If key is not found, the function returns NULL.

That means bsearch doesn't give me the position for inserting a new number .

 

by: thienpnguyenPosted on 2002-02-06 at 16:35:58ID: 6784288

>>> glebspy

Could you check again ? Maybe, that code has problem with

case 1 :
   SortedArray[] = { 1, 3 }
   numEle = 2
   target = 2

case 2 :
   SortedArray[] = {  1 }
   numEle = 1
   target = 3
   

Thank for helping .

 

by: glebspyPosted on 2002-02-06 at 19:32:08ID: 6784559

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[current_Divider])
        {
          current_Upper_Bound=current_Divider;
        }
      else
        {
          current_Lower_Bound=current_Divider+1;
        }
     }
  return current_Lower_Bound;
}

 

by: RobalitoruPosted on 2002-02-07 at 00:12:10ID: 6784968

  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...

 

by: RobalitoruPosted on 2002-02-07 at 00:19:44ID: 6784979

Sorry, my mistake, I didn't check close enough.
I ussually do this

(current_Lower_Bound + current_Upper_Bound) / 2;

so that's why a wrote the above.

Sorry glebspy.

But the last comment still stands.

 

by: smnahaPosted on 2002-02-07 at 02:27:44ID: 6785170

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.

 

by: AxterPosted on 2002-02-07 at 03:53:34ID: 6785283

You should still be able to use the built-in STD functions for this.

Try the following:

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;
}

 

by: AxterPosted on 2002-02-07 at 03:55:19ID: 6785287

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)], 9);
     int xi12 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 12);
     int xi15 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 15);
     int xi0 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 0);
     int xi20 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 20);
     int xi21 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 21);
     int xi22 = FindInsertionPoint(&A[0], &A[sizeof(A)/sizeof(int)], 22);

     return 0;
}

 

by: RobalitoruPosted on 2002-02-07 at 05:28:08ID: 6785424

  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?

 

by: MFCRichPosted on 2002-02-07 at 05:45:37ID: 6785461

int bsearch(int *array, int size, int target)
{
  int bottom = 0;
  int top = size;

  while (top > bottom)
  {
    int middle = (top + bottom) / 2;

    if (target == array[middle])
      return middle;

    if (target < array[middle])
      top= middle -1;
    else
      bottom= middle + 1;
  }

  return -1;   // not found
}

 

by: MFCRichPosted on 2002-02-07 at 05:47:45ID: 6785464

Whooops!!

>> while (top > bottom)

should be

>> while (top >= bottom)

 

by: AxterPosted on 2002-02-07 at 06:22:01ID: 6785579

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;
}

 

by: MFCRichPosted on 2002-02-08 at 06:23:24ID: 6788260

The question was about the binary search algorithm and I think my code demonstrates it.

 

by: AxterPosted on 2002-02-08 at 06:40:20ID: 6788322

>>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.

 

by: saravana_rajanPosted on 2002-02-09 at 06:04:33ID: 6790656

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 );
}

 

by: AxterPosted on 2002-02-09 at 14:28:31ID: 6791426

thienpnguyen,
Are you still there?

 

by: mbenassorPosted on 2002-02-10 at 02:53:33ID: 6792061

I think Robalitoru has a point, the real problem is to insert the new number into the correct position.
The code he suggested will do it in best time O(n) and with binary search O(log(n))+O(n)

 

by: AxterPosted on 2002-02-10 at 04:11:08ID: 6792094

mbenassor,
>>The code he suggested will do it in best time O(n) and
>>with binary search O(log(n))+O(n)

The code he suggested is NOT the best time.  A binary search is much faster.

 

by: AxterPosted on 2002-02-10 at 04:24:55ID: 6792108

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.

 

by: mbenassorPosted on 2002-02-12 at 13:37:29ID: 6797788

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.

 

by: AxterPosted on 2002-02-13 at 08:18:13ID: 6799537

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.

 

by: thienpnguyenPosted on 2002-02-17 at 10:53:21ID: 6805717

Sorry experts, I will come back to work in next week.
At that time, I will decide what is the best comment .

Thank for helping .

 

by: thienpnguyenPosted on 2002-02-26 at 00:29:32ID: 6826833

Thank experts .

In my opinion, when we evaluate big O for sort algorithm, we only count on comparing operator .

Finally, I accept  glebspy's comment .

I give 80 points to Axter for showing how to use build in std function, 50 points for Robalitoru.

Thank again to all experts.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...