Now the important thing to note here is that Binary Search only has a meaning when your input is sorted in some way, using some parameter as basis for sorting. This program implements binary search for a set of integers, sorted in ascending order. Binary search on an unsorted input makes no sense as if you first sort it and then reveal its position, the position has changed from what you initially gave as input, and is therefore, meaningless.
This should be the one your teacher will ask you to make. If its any different, please post a comment, I will try to make you a custom one according to your needs.
#include <iostream.h> #include <conio.h> int binarySearch(int*, int, int, int); int main() { int *sArray, mSize, i, elem, index; cout<<"\n Enter the maximum size of array : "; cin>>mSize; sArray = new int[mSize]; cout<<"\n Enter the elements of the array, sorted in ascending order : \n"; for (i=0; i<mSize; i++) { cin>>sArray[i]; } cout<<"\n Enter the element to be searched : "; cin>>elem; index = binarySearch (sArray, 0, mSize-1, elem); if (index < 0) { cout<<"\n Element not found"; } else { cout<<"\n The element was found at index "<<index; } getch(); } int binarySearch(int sArray[], int first, int last, int elem) { while (first < last) { int mid = (first + last) / 2; if (elem > sArray[mid]) { first = mid + 1; } else if (elem < sArray[mid]) { last = mid - 1; } else { return mid; } } return -(first + 1); }