Asked by
AL MaMun (4 Golds)
Friday, 31 Jul 2020, 04:55 PM
at (Education
Tutorials)
|
|
|
|
#include<bits/stdc++.h> int action(int A[], int n, int x) { int left, right, mid; left = 0; right = n-1; while(left <= right) { mid = (left + right)/2; if(A[mid] == x) return mid; if(x > A[mid]) left = mid + 1; else right = mid - 1; } return -1; } int main() { int a[10] = {1, 3, 5, 9, 12}; /// array must be sorted int r = action(a, 5, 12); if(r!=-1) printf("Found"); else printf("Not Found"); return 0; } |
C Program of Binary search algorithm : #include<iostream> using namespace std; int main() { int a[1000], beg, end, mid, i, n, s; cout<<"Enter n\n"; cin>>n; cout<<"Enter Number (small to big sorted must)\n"; for(i=1; i<=n; i++) { cin>>a[i]; } cout<<"What search?\n"; cin>>s; beg=1; end=n; mid=(beg+end)/2; while(beg<=end && a[mid]!=s) { if(a[mid]<s) beg=mid+1; else beg=mid-1; mid=(beg+end)/2; } if(a[mid]==s) cout<<"Data Found at "<<mid<<" position\n"; else cout<<"Data not found"; return 0; } |