Recursive Binary Search coderinme

Recursive Binary Search coderinme

create a class to represent an integer array of size n (value of n to be
inputted at run time). Include member functions (i) to input the array elements,
(ii) to sort the array elements in ascending order, (iii) to display the array and
(iv) to find the location of a given item in the array using recursive binary search
method.
Write a C++ program to use this class.

#include<iostream.h>
#include<conio.h>
class Array
{
int a[10],n;
public:
void input()
{
cout<<"Enter the size of array: ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"enter the "<<i+1<<" elements of array: ";
cin>>a[i];
}
}
void arraysort()
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void disp()
{
cout<<endl<<"Your sorted array is "<<endl;
for(int i=0;i<n;i++)
{
cout<<" "<<a[i];
}
cout<<endl;
}
int binary_search(int c)
{
int beg=0,end=n-1,mid;
while(beg<=end)
{
mid=(beg+end)/2;
if(c==a[mid])
return mid;
else if(c<a[mid])
end=mid-1;
else
beg=mid+1;
}
return -1;
}
};
int main()
{
Array a1;
int k,num;
a1.input();
a1.arraysort();
a1.disp();
cout<<endl<<"Enter the element you want to search: ";
cin>>num;
k = a1.binary_search(num);
if(k==-1)
cout<<"Given element is not found in the array";
else
cout<<"Given element is present in the array at position: "<<k+1;
getch();
return 0;
}

For more programs in C++, visit our C++ Archives

Recursive Binary Search coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.