使用重复项的java二进制搜索,返回所有匹配项
(使用java)我创建了一个地址簿,还有一个菜单,您可以从中选择,在地址簿中执行不同的操作。选择菜单项2,您可以在书中搜索姓氏为您想要搜索的任何成员(从控制台输入)。我在通讯录中查找通讯录中的姓氏。我正在搜索的一些名称有多个。当我进行二进制搜索(强制为二进制)时,我只返回其中一个名称,而不是返回与我的搜索名称匹配的所有名称。这是我的密码:使用重复项的java二进制搜索,返回所有匹配项,java,Java,(使用java)我创建了一个地址簿,还有一个菜单,您可以从中选择,在地址簿中执行不同的操作。选择菜单项2,您可以在书中搜索姓氏为您想要搜索的任何成员(从控制台输入)。我在通讯录中查找通讯录中的姓氏。我正在搜索的一些名称有多个。当我进行二进制搜索(强制为二进制)时,我只返回其中一个名称,而不是返回与我的搜索名称匹配的所有名称。这是我的密码: case '2': //search by last name// only returning 1 person.... name.la
case '2': //search by last name// only returning 1 person....
name.lastName="";
System.out.println("Please enter the last name of the person you
are looking for.");
name.lastName = console.next();
int find = binarySearchLast(name);
System.out.println(find);
System.out.println(bookMembers[find]);
process();
break;
private int binarySearchLast(ExtPerson name)
{
int first = 0;
int last = nMembers; //number of people in the book
int mid = 0;
boolean found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
//System.out.println("This is the mid : "+mid);
if (bookMembers[mid].lastName.compareTo(name.lastName)==0)
found = true;
else if (bookMembers[mid].lastName.compareTo(name.lastName)<0)
first = mid + 1;
else
last = mid - 1;
//System.out.println("This is the mid : "+mid);
}
if (!found)
mid = -1; //it is an unsuccessful search
// System.out.println("This is the mid : "+mid);
return mid;
}//end binarySearch
案例“2”://按姓氏搜索//仅返回1人。。。。
name.lastName=“”;
System.out.println(“请输入您需要的人的姓氏
你在找什么;
name.lastName=console.next();
int find=binarySearchLast(名称);
System.out.println(find);
System.out.println(bookMembers[find]);
过程();
打破
私有int binarySearchLast(ExtPerson名称)
{
int first=0;
int last=n成员;//书中的人数
int-mid=0;
布尔值=false;
while(first只需搜索列表,而无需找到条件。找到的条件就是停止循环的条件,只提供第一个找到的项
while (first <= last)
{
mid = (first + last) / 2;
//System.out.println("This is the mid : "+mid);
if (bookMembers[mid].lastName.compareTo(name.lastName)==0)
// do something, maybe add to a ist of found names or just print
else if (bookMembers[mid].lastName.compareTo(name.lastName)<0)
first = mid + 1;
else
last = mid - 1;
//System.out.println("This is the mid : "+mid);
}
while(首先您只能从一个方法返回一个int
值,因此,在某个时候,您必须进行额外的工作…以扩展搜索
二进制搜索不一定会找到第一个、最后一个或任何其他特定结果……因此,您必须做的第一件事是-切换到“好”点,这对于“第一个”匹配是有意义的:
if (!found)
mid = -1; //it is an unsuccessful search
// System.out.println("This is the mid : "+mid);
while (mid > 0 && bookMembers[mid].lastName.equals(bookMembers[mid-1].lastName)) {
mid--;
}
return mid;
然后,在调用代码中,可以执行相反的操作:
int findfrom = binarySearchLast(name);
int findto = findfrom + 1;
while (findto < bookMembers.length && bookMembers[findfrom].lastName.equals(bookMembers[findto].lastName)) {
findto++;
}
// the values findfrom (inclusive) to findto (exclusive) match.
int findfrom=binarySearchLast(名称);
int findto=findfrom+1;
while(findto
当我这么做的时候,我试着按照你说的那样做,只是打印出名字,但它陷入了一个无限循环,只打印出第一次找到名字的时候。首先,我想写的是,非常感谢!我也不应该在那里锁定美元大写字母……想想看,我听说这意味着大喊大叫。我的道歉,你是这样的目前陷入无限循环?