Binary Search.

Hey guys,

This is another post regarding the data structure and algorithm stuff. As I said in my earlier post, that as we are having data structures and algorithm in the upcoming semester I will be covering most of them here through my blog as to help some of you out there and I could also get a better understanding of things happening around. Also, this could be a sneak peek note for me as well 😛

Binary search is a search algorithm, which finds an element in the nth position inside a sorted array.

So here is the code,


int main()
	int n, i, arr[50], search, first, last, middle;

	cout << "Enter total number of elements :";
	cin >> n;

	cout << "Enter the array elements in sorted manner :";
	  for (i=0; i<n; i++)

	cout<<"Enter a number to find :";

	first = 0;
	last = n-1;
	middle = (first+last)/2;

	while (first <= last)
		if(arr[middle] < search)
			first = middle + 1;

		else if(arr[middle] == search)
			cout << search<<" found at location " << middle+1 << "\n";
			 last = middle - 1;
		middle = (first + last)/2;
	if(first > last)
		cout << "Not found! " << search << " is not present in the list.";
  return 0;

That’s it guys,

Cheers 🙂


Leave a Reply

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

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s