Over a million developers have joined DZone.

Binary Search Demo Program

·


//
// binary_search.cpp
//
// Demo program of binary search.


#include 						// uses printf 
#include 

int binary_search(int data[],int search_item,int length)
{
  int min =-1;
  int max = length;
  while(true)
  {
    // found condition.
    if(data[(min+max)/2]==search_item)
      return (min+max)/2;
    // termination condition.
    if(min==max)
    {
      return -1;
    }
    // else
    if(data[(min+max)/2]=MAX_ARRAY_SIZE)
      exit(0);
    count++;
  }
  

  // get the value that you need to search.
  int search;
  printf("Plese enter the value that you need to Search");
  scanf("%i",&search);
 
  // search.
  int result;
  if((result=binary_search(int_array,search,count))==-1)
  {
    printf("the value %i does not found in the array\n",search);
  }else{
    printf("the value %i is located at index %i\n",search,result);
  } 

  return 0;
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}