Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- int Binary_Search (int n,int num[],int newValue);
- int main()
- {
- int n,i,newValue,result;
- cout << "Enter Array Size: ";
- cin >> n;
- int num[n];
- cout << "Enter Values....." <<endl;
- for(i=0; i<n; i++)
- {
- cin >> num[i];
- }
- cout << "Input a Number to search: ";
- cin >> newValue;
- result = Binary_Search(n,num,newValue);
- if(result==-5)
- {
- cout << "Not Found" <<endl;
- }
- else
- {
- cout << "Found at Index " << result;
- }
- return 0;
- }
- int Binary_Search (int n, int num[],int newValue)
- {
- int last,first=0,mid;
- last = n-1;
- while(first <= last)
- {
- mid = (first+last)/2;
- if(num[mid] == newValue)
- {
- return mid;
- }
- else if(newValue > num[mid])
- {
- first = mid + 1;
- }
- else
- {
- last = mid - 1;
- }
- }
- return -5;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement