binary search
Posted: Tue Jul 07, 2015 1:43 am
hi im a beginer
can anybody help me to convert this code (c++) to ruby(works in flowstone) ??
can anybody help me to convert this code (c++) to ruby(works in flowstone) ??
Code: Select all
#include <conio.h>
#include <iostream.h>
main()
{
int n;
cout<<"array size???" ;
cin>>n;
cout << "_____________";
cout<<endl;
int a[n];
for(int i=0;i<n;i++)
{
cin>> a[i];
}
cout<<endl;
cout << "_____________";
cout<<endl;
for(int i=0;i<n;i++) //sort
{
for(int j=0;j<n-1;j++)
{
if(a[j+1]>a[j])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0;i<n;i++) //namayesh
{
cout<<a[i]<<" ";
}
cout<<endl;
cout << "_____________";
cout<<endl;
int f;
cin>>f;
int start=0; //Binary search
int end=n-1;
while(start<=end)
{
int mid=(start+end)/2;
if(a[mid]==f)
{
cout<<"found at "<<mid;
break;
}
if(a[mid]<f)
end=mid-1;
else if(a[mid]>f)
start=mid+1;
}
if(start>end)
cout<<"Not found!";
getch();
}