#include <bits/stdc++.h>
using namespace std;
int findelements(int *a, int n, int K)
{
int l = 0, r = n - 1, mid;
while (l <= r)
{
if (l == r)
{
if (a[l] == K)
return 1;
else
return 0;
}
else if (l == r - 1)
{
if (a[l] == K || a[r] == K)
return 1;
else
return 0;
}
else
{
mid = l + (r - l) / 2;
if (a[mid] == K)
return 1;
else if (a[mid] < K)
r = mid - 1;
else
l = mid + 1;
}
}
return 0;
}
int main()
{
int K, count = 0, n;
cout << "enter size of elements\n"; // enter array length
cin >> n;
int *a = (int *)(malloc(sizeof(int) * n));
cout << "enter elements \n"; // fill the array
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
cout << "enter the element to search,K" << endl;
cin >> K;
if (findelements(a, n, K))
cout << "element is found\n";
else
cout << "element not found\n";
return 0;
}
Output
enter the size of elements
5
enter elements
1
2
5
4
7
enter the element to search,K
4
element is found
0 Comments