2 answers
Best answer
Output::

Below code is executed on gdb turbo c++ compiler , it takes 10 input of given number then sort by binary search technique
#include<iostream.h>
int main()
{
int i, arr[10], num, first, last, middle;
cout<<"Enter 10 Elements (in ascending order): ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter Element to be Search: ";
cin>>num;
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
cout<<endl;
return 0;
}Answer: Initialize a sorted float array of 10 numbers in the program, read the number to search, and repeatedly compare it with the middle element, halving the search range each time.
#include <iostream>
using namespace std;
int main()
{
float arr[10] = {1.5, 2.25, 3.0, 4.75, 5.5,
6.1, 7.8, 8.25, 9.0, 10.5}; // sorted
float num;
int first = 0, last = 9, mid, pos = -1;
cout << "Enter the number to search: ";
cin >> num;
while (first <= last) {
mid = (first + last) / 2;
if (arr[mid] == num) {
pos = mid;
break;
}
else if (arr[mid] < num)
first = mid + 1; // search right half
else
last = mid - 1; // search left half
}
if (pos != -1)
cout << "Number found at position " << pos + 1 << endl;
else
cout << "The number is not found" << endl;
return 0;
}How it works: binary search needs a sorted array. first and last mark the part still to be searched. Each time, the middle element arr[mid] is compared with num: if equal, the position is found; if num is larger, only the right half can contain it, so first = mid + 1; otherwise last = mid - 1. If first passes last, the number is not in the array.
Example: searching 7.8 checks 5.5 (index 4), then 8.25 (index 7), then 6.1 (index 5), then 7.8 (index 6) → "Number found at position 7". Binary search only searches; it does not sort. Exact == works here because the number typed matches a stored value exactly.
Your answer
Log in or create a free account to answer this question.