If you have a problem or need to report a bug please email : support@dsprobotics.com
There are 3 sections to this support area:
DOWNLOADS: access to product manuals, support files and drivers
HELP & INFORMATION: tutorials and example files for learning or finding pre-made modules for your projects
USER FORUMS: meet with other users and exchange ideas, you can also get help and assistance here
NEW REGISTRATIONS - please contact us if you wish to register on the forum
Users are reminded of the forum rules they sign up to which prohibits any activity that violates any laws including posting material covered by copyright
binary search
2 posts
• Page 1 of 1
binary search
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();
}
- looji
- Posts: 1
- Joined: Fri May 29, 2015 11:15 am
Re: binary search
The question is if you gain any advantage from it. Binary search, a divide and conquer algorithm, is very stable and therefore the best choice for very large arrays. However, in pure Ruby the code gets interpreted, while the built-in search methods are compiled c-code.
binary search needs a sorted array to start with. You sort an array simply by using
For the binary search, there's a premade code block on codecodex, using recursiveness:
If this doesn't help you, please provide a description of how you want to make use of it.
binary search needs a sorted array to start with. You sort an array simply by using
- Code: Select all
myarray.sort!
For the binary search, there's a premade code block on codecodex, using recursiveness:
- Code: Select all
def binary_search(array, key, low=0, high=array.size-1)
return -1 if low > high
mid = (low + high) / 2
return mid if array[mid]==key
if array[mid] > key
high = mid - 1
else
low = mid + 1
end
binary_search(array, key, low, high)
end
If this doesn't help you, please provide a description of how you want to make use of it.
"There lies the dog buried" (German saying translated literally)
- tulamide
- Posts: 2714
- Joined: Sat Jun 21, 2014 2:48 pm
- Location: Germany
2 posts
• Page 1 of 1
Who is online
Users browsing this forum: No registered users and 80 guests