In: Computer Science
Binary_search(int a[], int size)
{
……….// binary search and return
}
Selection_Sort(int a[], int z)
{
…..// do the selection sort
}
main()
{
Selection_Sort(array, size);
Binary_Search(array, item);
}
#include <iostream>
using namespace std;
void Selection_Sort(int a[], int z)
{
int i,j,min_pos,temp;
for (i=0;i<z-1;i++)
{
//find the minimum element of next unsorted array
min_pos=i;
for (j=i+1;j<z;j++)
{
if (a[j]<a[min_pos]) //if it is minimum take position
min_pos=j;
}
//swap the found minimum element with the first element
temp=a[min_pos];
a[min_pos]=a[i];
a[i]=temp;
}
}
int Binary_Search(int a[],int item,int size)
{
int mid,l,r;
l=0;
r=size;
while (l<=r) {
mid=l+(r-l)/2;
//check if the middle value is our element
if(a[mid]==item)
return mid;
//If x greater than mid check in right half
if (a[mid]<item)
l=mid+1;
//If x is smaller than mid check in left half
else
r=mid-1;
}
return -1;//if the element is not present
}
int main()
{
int a[]={5,7,1,4,9,10,3};
Selection_Sort(a,7);
int pos=Binary_Search(a,5,7);
if(pos!=-1)
cout<<"The element found at "<<pos;
else
cout<<"The element is not found";
return 0;
}
The Binary search function shold pass the size of array to function because it is not possible to calculate the size inside a function other than main.
comment if any doubts