search.java
来自「二分查找的应用」· Java 代码 · 共 56 行
JAVA
56 行
import java.util.Arrays;
public class Search {
int comparisons=0;
private Search() {}
public static Person binary(Person[ ] collection, String key) {
if (collection != null) {
int left =0;
int right = collection.length-1;
while ( (left <= right) ) {
int mid = (left + right) /2;
int c = key.compareTo(collection[mid].getFirstName());
if (c<0) {
right=mid-1;
}
else if (c>0){
left = mid + 1;
}
else
{
return collection[mid];
}
}
}
return null;
}
public static Person sequential(Person[ ] collection, String key){
if (collection!= null) {
for (int i = 0; i < collection.length; i++) {
if (collection[i].getFirstName()== key) {
// found the key
return collection[i];
}
}
}
return null;
}
// return the number of comparisons made in most recent search
public int getComparisons() {
return comparisons;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?