Simple Binary Searching Program in C++
Definition
Binary search is a quickest search algorithm that finds the position of a target value within a sorted array
Also Called,
- half-interval search
- logarithmic search
- binary chop
Simple Binary Searching Program
/* Simple Binary Search Program Using Functions in C++*/
/* Data Structure C++ Programs,C++ Array Examples */
#include <iostream>
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
using namespace std;
int main() {
int arr_search[MAX_SIZE], i, element;
int f = 0, r = MAX_SIZE, mid;
cout << "Simple C++ Binary Search Example - Array\n";
cout << "\nEnter " << MAX_SIZE << " Elements for Searching : " << endl;
for (i = 0; i < MAX_SIZE; i++)
cin >> arr_search[i];
cout << "\nYour Data :";
for (i = 0; i < MAX_SIZE; i++) {
cout << "\t" << arr_search[i];
}
cout << "\nEnter Element to Search : ";
cin>>element;
while (f <= r) {
mid = (f + r) / 2;
if (arr_search[mid] == element) {
cout << "\nSearch Element : " << element << " : Found : Position : " << mid + 1 << ".\n";
break;
} else if (arr_search[mid] < element)
f = mid + 1;
else
r = mid - 1;
}
if (f > r)
cout << "\nSearch Element : " << element << " : Not Found \n";
getch();
}
Sample Output
Simple Binary Search Example - Array
Enter 5 Elements for Searching :
12
34
56
78
90
Enter Element to Search : 78
Search Element : 78 : Found : Position : 4.
Read More Articles
- Simple Merge Sort Program in C++
- Scope Resolution Operator In C++
- Simple Program for Virtual Functions Using C++ Programming
- Simple Class Example Program For Find Prime Number In C++
- Simple Example Program For Parameterized Constructor In C++
- Define Constructor in Outside Class Example Program In C++
- Simple Example Program For Copy Constructor In C++
- Simple Program for Function Overloading Using C++ Programming
- Simple Program for Single Inheritance Using C++ Programming
- Simple Program for Inline Function without Class Using C++ Programming
- Factorial Using Function Example Program In C++
- Simple Example Program For Constructor Overloading In C++
- Simple Example Program For Constructor In C++
- Simple Addition ( Add Two Integers ) Example Program
- Simple Example Program for Inline Function Using C++ Programming
- Simple Program for Read user Input Using cin
- Factorial Using Loop Example Program In C++
- Simple Stack Program in C++ Programming
- Simple Program for Friend Function Using C++ Programming
- Simple Program for Static Data and Member Function Using C++ Programming
- Simple Program for Unary Operator Overloading Using C++ Programming
- Simple Program for Multiple Inheritance Using C++ Programming
- Do While Loop Example Program In C++
- Simple Copy Constructor Example Program For Find Factorial In C++
- Simple Program for Function Template Using C++ Programming