0% found this document useful (0 votes)
8 views5 pages

Binary Search Record

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Binary Search Record

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

SOURCE CODE:

#include<iostream>
#include<cstring>
using namespace std;
int n, count;
void BubbleSort(string arr[])
{
int i,j;
for(i=0; i < n-1; i++)
{
for(j=0; j < n-i-1; j++)
{
if(arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
}
}
}
}
int BinarySearch(string arr[], int low, int high, string sch)
{
count++;
cout << "\nFunction Call Count - " << count << ":";
if(low > high)
{
cout << "\nArray is Completely Checked, terminating the function...\n";
return -1;
}
int mid = (low + high)/2;
cout << " Current Middle Element - " << arr[mid];
if(arr[mid] == sch)
{
cout << "\nSearch Element Matches with the Current Middle Element, returning to
the Main Function...\n";
return mid;
}
else if(arr[mid] > sch)
{
cout << "\nSearch Element is Lesser than Current Middle Element, calling the
BinarySearch Function Recursively...\n";
return BinarySearch(arr, low, mid-1, sch);
}
else
{
cout << "\nSearch Element is Greater than Current Middle Element, calling the
BinarySearch Function Recursively...\n";
return BinarySearch(arr, mid+1, high, sch);
}
}
int main()
{
cout << "\nEnter Number of Array Elements: ";
cin >> n;
string arr[n];
cout << "\nEnter " << n << " Array Elements: \n";
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
BubbleSort(arr);
cout << "\nSorted Array Elements: ";
for(int i = 0; i < n; i++)
{
cout << arr[i];
if( i < n-1)
{
cout << ", ";
}
}
cout << "\n\nASCII Value of the Sorted Array Elements: ";
for(int i = 0; i < n; i++)
{
cout << " (" << arr[i] << " | " << int(arr[i][0]) << ")";
if( i < n-1)
{
cout << ", ";
}
}
cout << "\n\nEnter Element to be searched: ";
string sch;
cin >> sch;
int index = BinarySearch(arr, 0, n-1, sch);
if(index == -1)
{
cout << "\nElement \"" << sch << "\" is not present in the Array";
}
else
{
cout << "\nElement \"" << sch << "\" is present in the index \"" << index << "\"";
}
return 0;
}
INPUT AND OUTPUT:

You might also like