TIME COMPLEXITY:
#include<iostream> using namespace std; ///binary search using recursion... int binarysearch(int *a,int no,int i,int n){ if(i<n){ int mid=(i+n)/2; if(a[mid]==no){ return 1; } else if(no<a[mid]){ return binarysearch(a,no,0,mid-1); } else if(no>a[mid]){ return binarysearch(a,no,mid+1,n); } } return 0; } int main() { int *a,n,no; cout<<"enter no of elements in an array"; cin>>n; a=new int[n]; ///getting array elements ///important condition :: the array should be in sorted order to perform binary search.. for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"enter the element to be searched"; cin>>no; ///call binary search function if(binarysearch(a,no,0,n)){ cout<<"FOUND\n"; } else{ cout<<"NOT FOUND\n"; } return 0; }
O(log n)
Next-Binary Search-Iterative
Comments
Post a Comment