BINARY SEARCH
C++
........
#include<iostream>
using namespace std;
int main()
{
int a[100], n, i, beg, end, mid, item;
cout << "Enter No. of Elements : ";
cin >> n;
cout << "\nEnter Elements in Sorted Order :\n";
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
cout << "\nEnter Item you want to Search : ";
cin >> item;
beg = 1;
end = n;
mid = (beg + end) / 2;
while (beg <= end && a[mid] != item)
{
if (a[mid] < item)
beg = mid + 1;
else
end = mid - 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
{
cout << "\nElement found at location : " << mid;
}
else
{
cout << "Element not found";
}
return 0;
}
========
Output
========
Enter No. of Elements : 3
Enter Elements in Sorted Order :
2
3
5
Enter Item you want to Search : 3
Element found at location : 2
C++
........
#include<iostream>
using namespace std;
int main()
{
int a[100], n, i, beg, end, mid, item;
cout << "Enter No. of Elements : ";
cin >> n;
cout << "\nEnter Elements in Sorted Order :\n";
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
cout << "\nEnter Item you want to Search : ";
cin >> item;
beg = 1;
end = n;
mid = (beg + end) / 2;
while (beg <= end && a[mid] != item)
{
if (a[mid] < item)
beg = mid + 1;
else
end = mid - 1;
mid = (beg + end) / 2;
}
if (a[mid] == item)
{
cout << "\nElement found at location : " << mid;
}
else
{
cout << "Element not found";
}
return 0;
}
========
Output
========
Enter No. of Elements : 3
Enter Elements in Sorted Order :
2
3
5
Enter Item you want to Search : 3
Element found at location : 2
The complete Facebook Marketing for Beginners
https://www.udemy.com/course/best-course-82/?couponCode=063FC56D95D5031271FE
The Complete Digital Marketing Course for Beginners
https://www.udemy.com/course/make-money-using/?couponCode=E4F1C09C42F7C9BB08F8
β£οΈshare & support us β£οΈ
ββ @geekcode ββ
https://www.udemy.com/course/best-course-82/?couponCode=063FC56D95D5031271FE
The Complete Digital Marketing Course for Beginners
https://www.udemy.com/course/make-money-using/?couponCode=E4F1C09C42F7C9BB08F8
β£οΈshare & support us β£οΈ
ββ @geekcode ββ
Udemy
Online Courses - Learn Anything, On Your Schedule | Udemy
Udemy is an online learning and teaching marketplace with over 213,000 courses and 62 million students. Learn programming, marketing, data science and more.