[英]How do you use a binary search using only words and not numbers?
I was asked to use binary search to find specific words in a file that we read. 我被要求使用二进制搜索在我们读取的文件中查找特定的单词 。
The issue I do not understand is how to use a binary search when you are looking for words and not numbers . 我不明白的问题是,在查找单词而不是数字时如何使用二进制搜索。
Binary search operates on sorted inputs . 二进制搜索对分类的输入进行操作 。 You can define an order also on words, not only on values.
您不仅可以根据值,还可以按单词定义顺序 。
For example the lexicographical order . 例如字典顺序 。 In Java this is even implemented as the natural order of
String
s. 在Java中,这甚至被实现为
String
的自然顺序 。 So you can do "text1".compareTo("text2")
and it returns the order. 因此,您可以执行
"text1".compareTo("text2")
并返回顺序。
A small illustration of binary search: 二进制搜索的一个小例子:
As you see, the only thing to decide in the algorithm is the order between two objects. 如您所见,在算法中唯一要决定的就是两个对象之间的顺序。 For example, from the image,
7 < 14
and 7 > 6
. 例如,从图像中,
7 < 14
和7 > 6
。 As said, you can also do this for String
s. 如前所述,您也可以对
String
执行此操作。 Indeed for everything for which you define an order . 事实上, 一切为您定义的订单 。
Actually many classes in Java (more than 150
) implement a natural order , they are listed under the interface Comparable
( documentation ), they all provide a compareTo
method with a meaningful order . 实际上,Java中的许多类(超过
150
)实现自然顺序 ,它们在Comparable
接口( 文档 )下列出,它们都提供具有有意义顺序的compareTo
方法。
Think of looking up a word in the dictionary; 考虑在字典中查找一个单词; this is an example of binary search.
这是二进制搜索的示例。
For example, lets look up "eunoia": 例如,让我们查找“ eunoia”:
This all works because the dictionary is well-ordered , we all agree that A is the 1st letter, B is the 2nd, etc. Another way to look at it is that the Alphabet is the same thing as the numbers [0 - 25] just with different names. 所有这些都是有效的,因为字典是有序的 ,我们都同意A是第一个字母,B是第二个字母,依此类推。另一种查看方式是字母表与数字[0-25]相同只是用不同的名字。
Binary Search for string Implemented in C. 二进制搜索字符串,在C中实现。
char *lineptr[MAXLINE] //Array of char pointers stores the address of string
int binsrch(char srch[],int low,int high)
{
int mid;
if(high>=low){
mid=(low+high)/2;
if(strcmp(srch,lineptr[mid])<0) //compare string stored in srch and lineptr[mid]
return binsrch(srch,low,mid-1,count);
else if(strncmp(srch,lineptr[mid],count)>0)
return binsrch(srch,mid+1,high,count);
else
return mid; // Found
}
return -1; //Not found
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.