Binary Search Algorithm Implementation in C++, Thesis of Data Structures and Algorithms

The implementation of a binary search algorithm in c++. The user is prompted to enter the number of elements in the array and each element, followed by the number to be searched. The algorithm then performs a binary search on the array to find the location of the number, if it exists.

Typology: Thesis

2017/2018

Uploaded on 10/25/2018

wahid-afridi
wahid-afridi 🇵🇰

4 documents

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
using namespace std;
int main()
{
int count, i, arr[30], num, first, last, middle;
cout<<"how many elements would you like to enter?:";
cin>>count;
for (i=0; i<count; i++)
{
cout<<"Enter number "<<(i+1)<<": ";
cin>>arr[i];
}
cout<<"Enter the number that you want to search:";
cin>>num;
first = 0;
last = count-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < num)
{
first = middle + 1;
}
else if(arr[middle] == num)
{
cout<<num<<" found in the array at the location "<<middle+1<<"\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<num<<" not found in the array";
}
return 0;
}
Output:
how many elements would you like to enter?:5
Enter number 1: 12
Enter number 2: 45
Enter number 3: 8
Enter number 4: 9
Enter number 5: 100
Enter the number that you want to search:8
8 found in the array at the location 3
pf2

Partial preview of the text

Download Binary Search Algorithm Implementation in C++ and more Thesis Data Structures and Algorithms in PDF only on Docsity!

using namespace std;

int main() { int count, i, arr[30], num, first, last, middle; cout<<"how many elements would you like to enter?:"; cin>>count;

for (i=0; i<count; i++) { cout<<"Enter number "<<(i+1)<<": "; cin>>arr[i]; } cout<<"Enter the number that you want to search:"; cin>>num; first = 0; last = count-1; middle = (first+last)/2; while (first <= last) { if(arr[middle] < num) { first = middle + 1;

else if(arr[middle] == num) { cout<<num<<" found in the array at the location "<<middle+1<<"\n"; break; } else { last = middle - 1; } middle = (first + last)/2; } if(first > last) { cout<<num<<" not found in the array"; } return 0; } Output:

how many elements would you like to enter?: Enter number 1: 12 Enter number 2: 45 Enter number 3: 8 Enter number 4: 9 Enter number 5: 100 Enter the number that you want to search: 8 found in the array at the location 3