Binary Search in C++


This is a recursive binary search algorithm written in C++. It only works with presorted lists going up in value. If the value is not found, it says it is at position -1.

Bubble sort is a great way to sort small lists. You can see a bubble sort algorithm written in Java here:

Running

Source Code

main.cpp

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
int binary_search(vector<T> v, int from, int to, int value)
{
  if (from > to)
    return -1;
  int mid = (from + to) / 2;
  if (v[mid] == value)
    return mid;
  else if (v[mid] < value)
    return binary_search(v, mid + 1, to, value);
  else
    return binary_search(v, from, mid - 1, value);
}

int main(int argc, char** argv)
{
  int ints[] = {2, 3, 6, 8, 9, 10, 17, 19};
  vector<int> x (ints, ints + sizeof(ints) / sizeof(int));
  int location = binary_search(x, 0, x.size() - 1, 17);
  cout << "-1 means element not found.  First element is 0,\nsecond is 1, third is 2, etc.\n\n";
  cout << "ints[] {2, 3, 6, 8, 9, 10, 17, 19}\n17 is at " << location;
  double doubles[] = {5, 9, 22, 30, 35, 37, 38, 50, 67};
  vector<double> y (doubles, doubles + sizeof(doubles) / sizeof(double));
  location = binary_search(y, 0, y.size() - 1, 36);
  cout << "\n\ndoubles[] = {5, 9, 22, 30, 35, 37, 38, 50, 67}\n40 is at " << location;
  location = binary_search(y, 0, y.size() - 1, 50);
  cout << "\n50 is at " << location;
  return 0;
}
,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: