Code
#include <iostream>using namespace std;int main(){int n, x, i, pos, start=0, end, mid;int a[100];cout << "Enter the number of elements in the array: ";cin >> n;end = n-1;cout << "Enter the elements of the array (must be sorted)" << endl;for (i = 0; i < n; i++){cin >> a[i];}cout << endl;cout << "Enter element to search: ";cin >> x;while(start<=end){mid = (start+end)/2;if(a[mid] == x){cout << "Element is found at position " << mid + 1;exit (0);}else if(x < a[mid]){end = mid - 1;}else{start = mid + 1;}}cout << "Element is not found. " << endl;return 0;}
Output
Enter the number of elements in the array: 5
Enter the elements of the array
1
4
6
7
8
Enter element to search: 7
Element found at position 4
0 Comments
Post a Comment