二分查找排序的数组 [英] Binarysearch unsorted array

查看:198
本文介绍了二分查找排序的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人知道这个问题的答案Java的认证问题:

Hopefully someone knows the answer to this Java-Certification question:

public static void main(String[] args) {
 String[] sa = {"d", "c", "a", "b" };
 int x = Arrays.binarySearch(sa, "b");
 Arrays.sort(sa);
 int y = Arrays.binarySearch(sa, "b");
 System.out.println(x + " " + y);
}

这两种结果都是可能的? (选择两项。)

A)7 0

B)7 1

C)7 3

D)-1 0

E)-1 1

F)-1 3

Which two results are possible? (Choose two.)
A) 7 0
B) 7 1
C) 7 3
D) -1 0
E) -1 1
F) -1 3

唯一真正的答案是E)-1 1,因为如果你通过二进制搜索算法打,这是唯一可能的输出。但他们要我选两个...
所以,第二个必须是B)7 1,那么,因为排序数组中的第二的binarySearch总是返回 1

The only true answer is E) -1 1, because if you play through the binary-search-algorithm this is the only possible output. But they want me to choose two... So the second one have to be B) 7 1 then, because the second binarySearch in the sorted array will always return 1.

所以我的问题是,为什么B)7 1可能的结果呢?
更具体:?这怎么可能,即无序排列在第一的binarySearch返回7

So my Question is, why is B) 7 1 a possible result? More specific: How is it possible, that the first binarySearch in the unsorted array returns 7?

在此先感谢

推荐答案

这是一个有趣的问题。一个未排序的阵列上的二进制搜索的结果不确定,按照文档:

This is a trick question. The results of binary search on an unsorted array are undefined, as per documentation:

阵列必须进行排序(通过sort方法,以上)之前,在进行此调用。如果没有排序,结果是不确定的。

The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined.

这尤其意味着任何数字,其中包括7名,是公平的游戏。

This means in particular that any number, including seven, is fair game.

这是一个有序一项的结果是明确的:你会得到一个 1 。仿佛被施了魔法,只有两对 1 ,最终的答案就行了,所以 B 电子是选择考官期望你做。

The results on a sorted one are well-defined: you'll get a 1. As if by magic, there are only two pairs that end in 1 on the list of answers, so B and E is the choice the examiners expect you to make.

这篇关于二分查找排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆