C++ code for binary search


C++ code for binary search

This is C++ example code for the binary search.

#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;
void insertsort(int dataset[], int n);
int binsearch(int dataset[],int target,int n);

int main(){
   int arr[5]={23,2,3,34,6};
   int pos;
   pos=binsearch(arr,34,5);
   if(pos!=-1)
   cout<<"The target item was found at location:"<<pos<<".";
   else cout<<"The target item was not found in the list."<<endl;


   getch();
   return 0;

}

int binsearch(int dataset[],int target, int n){
insertsort(dataset,n);//make sure the list sorted
  int i;
  int pos=-1;
  bool found=false;

  if(target<dataset[n/2]){//look in the first half
  for(i=0;i<n/2 && found!=true;i++)
  if(target==dataset[i]){ found=true;pos=i;}
  }
  else{ //look in the second haft
  for(i=n/2;i<n && found!=true;i++)
  if(target==dataset[i]){ found=true;pos=i;}
  }


  return pos;
}

void insertsort(int dataset[], int n){
    int i,j;
    for(i=1;i<=n;i++){
    int pick_item=dataset[i];
    bool inserted=false;
    for(j=i-1;j>=0 && inserted!=true;){
      if(pick_item<dataset[j])
       {
         dataset[j+1]=dataset[j];
         j--;
         dataset[j+1]=pick_item;
         }
       else inserted=true;
      }
  }

}



Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.