//Searching an element through binary search in C++
#include<iostream>
using namespace std;
#define SIZE 10
int main()
{
int arr[SIZE];
int low, up, mid, item , i;
cout << "enter 10 Elements in SORTED Order" << endl;
for (i =0; i <SIZE; i++)
{
cin >> arr[i];
}
for (i =0 ; i < SIZE ; ++i)
cout << arr[i] << endl;
cout << "enter item to be searched\n";
cin >> item;
low = 0;
up = SIZE -1;
mid = -1;
while(low<= up && item != arr[mid] )
{
mid = (low + up)/2;
if (item < arr[mid])
up = mid -1;
if (item > arr[mid])
low = mid +1;
if (item == arr[mid])
cout << "your search element found at position:" << mid << endl;
if (low>up)
cout << "your search element not found" << endl;
}
return 0;
}
#include<iostream>
using namespace std;
#define SIZE 10
int main()
{
int arr[SIZE];
int low, up, mid, item , i;
cout << "enter 10 Elements in SORTED Order" << endl;
for (i =0; i <SIZE; i++)
{
cin >> arr[i];
}
for (i =0 ; i < SIZE ; ++i)
cout << arr[i] << endl;
cout << "enter item to be searched\n";
cin >> item;
low = 0;
up = SIZE -1;
mid = -1;
while(low<= up && item != arr[mid] )
{
mid = (low + up)/2;
if (item < arr[mid])
up = mid -1;
if (item > arr[mid])
low = mid +1;
if (item == arr[mid])
cout << "your search element found at position:" << mid << endl;
if (low>up)
cout << "your search element not found" << endl;
}
return 0;
}
result:
enter 10 Elements in SORTED Order
1 2 3 4 5 6 7 8 9 99
1
2
3
4
5
6
7
8
9
99
enter item to be searched
7
your search element found at position:6
No comments:
Post a Comment